Can I LINQ a JSON?

markzzz picture markzzz · Sep 12, 2013 · Viewed 50.9k times · Source

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

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

and I'd like to catch the field "url", using (maybe?) LINQ. I do many request as this, that differents a bit. So I won't to create a C# Class and deserialize it every time.

Is it a way to extract a single field? Thank you!

Answer

I4V picture I4V · Sep 12, 2013

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