Can I LINQ a JSON?

六月ゝ 毕业季﹏ 提交于 2019-11-27 04:09:53
I4V

No need for Linq, just use dynamic (using Json.Net)

dynamic obj = JObject.Parse(json);
Console.WriteLine((string)obj.picture.data.url);

Linq version would not be much readable

JObject jObj = JObject.Parse(json);
var url = (string)jObj.Descendants()
                    .OfType<JProperty>()
                    .Where(p => p.Name == "url")
                    .First()
                    .Value;

Documentation: LINQ to JSON

Parv Sharma

I would not recommend LINQ. I would recommend a JSON library such as newtonsoft.json.

So you can do this:

string json = @"{
  ""Name"": ""Apple"",
  ""Expiry"": "2008-12-28T00:00:00",
  ""Price"": 3.99,
  ""Sizes"": [
    ""Small"",
    ""Medium"",
    ""Large""
  ]
}";

JObject o = JObject.Parse(json);

string name = (string)o["Name"];

// Apple
JArray sizes = (JArray)o["Sizes"];
string smallest = (string)sizes[0];

// Small

Note:- this code has been copied from the samples present on the project site http://james.newtonking.com/pages/json-net.aspx

In a bind you could always deserialize the JSON and serialize it to XML, and load the XML in a XDocument. Then you can use the classic Linq to XML. When you are done take the XML, deserialize it, and serialize it back to JSON to JSON. We used this technique to add JSON support to an application that was originally built for XML, it allowed near-zero modifications to get up and running.

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