Can I LINQ JSON?

This is the JSON I get from a .NET request:

{ "id": "110355660738", "picture": { "data": { "url": "https://fbcdn-profile-a.akamaihd.net/hprofile-ak-prn2/1027085_12033235063_5234302342947_n.jpg", "is_silhouette": false } } } 

and I would like to catch the url field using (maybe?) LINQ. I make a lot of requests since this is a little different. Therefore, I will not create a C # class and deserialize it every time.

Is this a way to extract a single field? Thank!

+46
json c # linq linq-to-json
Sep 12 '13 at 7:43 on
source share
3 answers

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

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

Linq version will 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

+72
Sep 12
source share

I would not recommend LINQ. I would recommend a JSON library like 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 was copied from samples present on the project website http://james.newtonking.com/pages/json-net.aspx

+5
Sep 12 '13 at 7:45
source share

In bindings, you can always deserialize JSON and serialize it to XML and load the XML into an XDocument. Then you can use classic Linq for XML. When you're done, take the XML, deserialize it, and serialize it back to JSON in JSON. We used this technique to add JSON support to an application that was originally built for XML, and allowed us to get almost zero modifications to run and run.

0
Jun 03 '16 at 15:30
source share



All Articles