使用JObject和JProperty与JSON.Net 4.0 [英] Using JObject and JProperty with JSON.Net 4.0

查看:853
本文介绍了使用JObject和JProperty与JSON.Net 4.0的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想反序列化JSON格式为:

I'm trying to deserialize JSON in this format:

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

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

to a simple string array like this:

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

使用 JSON.NET 4.0

我已经得到它使用`CustomCreationConverter工作。

I've gotten it to work using the `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响应。

but this really seems like overkill, especially if I want to create one for many different json responses.

我试过使用 JObject ,但它似乎并不像我这样做是正确的:

I've tried using JObject but it doesn't seem like I'm doing it right:

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);
}



有没有更好的方式来做到这一点?

Is there a better way to do this?

推荐答案

有很多方法可以做到这一点,你有什么是好的。其他一些替代方案如下:

There are many ways you can do that, and what you have is fine. A few other alternatives are shown below:


  • 获取,而不是所有的孩子数组的第一个元素,

  • 使用 SelectToken 去第一个数组元素与一个单一的通话

  • Get the first element of the array, instead of all the children
  • Use SelectToken to go to the first array element with a single call

    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));


这篇关于使用JObject和JProperty与JSON.Net 4.0的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆