gpt4 book ai didi

c# - 在 JSON.Net 4.0 中使用 JObject 和 JProperty

转载 作者:太空狗 更新时间:2023-10-30 00:55:08 24 4
gpt4 key购买 nike

我正在尝试以这种格式反序列化 JSON:

{
"data": [
{
"installed": 1,
"user_likes": 1,
"user_education_history": 1,
"friends_education_history": 1,
"bookmarked": 1
}
]
}

像这样一个简单的字符串数组:

{
"installed",
"user_likes",
"user_education_history",
"friends_education_history",
"bookmarked"
}

使用 JSON.NET 4.0

我已经使用 `CustomCreationConverter' 让它工作了

public class ListConverter : CustomCreationConverter<List<string>>
{
public override List<string> Create(Type objectType)
{
return new List<string>();
}

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
var lst = new List<string>();

//don't care about the inital 'data' element
reader.Read();

while (reader.Read())
{
if (reader.TokenType == JsonToken.PropertyName)
{
lst.Add(reader.Value.ToString());
}
}
return lst;
}
}

但这真的看起来有点矫枉过正,特别是如果我想为许多不同的 json 响应创建一个。

我试过使用 JObject 但我似乎没有做对:

List<string> lst = new List<string>();
JObject j = JObject.Parse(json_string);
foreach (JProperty p in j.SelectToken("data").Children().Children())
{
lst.Add(p.Name);
}

有更好的方法吗?

最佳答案

您可以通过多种方式做到这一点,您所拥有的就可以了。下面显示了一些其他替代方案:

  • 获取数组的第一个元素,而不是所有的子元素
  • 使用SelectToken 一次调用转到第一个数组元素

        string json = @"{
    ""data"": [
    {
    ""installed"": 1,
    ""user_likes"": 1,
    ""user_education_history"": 1,
    ""friends_education_history"": 1,
    ""bookmarked"": 1
    }
    ]
    }";

    JObject j = JObject.Parse(json);

    // Directly traversing the graph
    var lst = j["data"][0].Select(jp => ((JProperty)jp).Name).ToList();
    Console.WriteLine(string.Join("--", lst));

    // Using SelectToken
    lst = j.SelectToken("data[0]").Children<JProperty>().Select(p => p.Name).ToList();
    Console.WriteLine(string.Join("--", lst));

关于c# - 在 JSON.Net 4.0 中使用 JObject 和 JProperty,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10542810/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com