Using JObject and JProperty with JSON.Net 4.0

懵懂的女人 提交于 2019-12-04 11:00:20

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

  • 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));
    
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!