Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I LINQ a JSON?

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!

like image 951
markzzz Avatar asked Sep 12 '13 07:09

markzzz


People also ask

Can JSON be used in C#?

Reading and writing JSON in C# is common these days.

What is JObject and JToken?

The JToken hierarchy looks like this: JToken - abstract base class JContainer - abstract base class of JTokens that can contain other JTokens JArray - represents a JSON array (contains an ordered list of JTokens) JObject - represents a JSON object (contains a collection of JProperties) JProperty - represents a JSON ...

What is JObject C#?

JObject. It represents a JSON Object. It helps to parse JSON data and apply querying (LINQ) to filter out required data. It is presented in Newtonsoft. Json.

What is LINQ in C# with example?

LINQ is the basic C#. It is utilized to recover information from various kinds of sources, for example, XML, docs, collections, ADO.Net DataSet, Web Service, MS SQL Server, and different database servers.


1 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 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

like image 115
I4V Avatar answered Oct 07 '22 11:10

I4V