What is the simplest C # function to parse a JSON string into an object?

What is the simplest C # function to parse a JSON string into an object and map it (C # XAML WPF)? (for example, an object with 2 arrays - arrA and arrB)

+49
json c # wpf
May 18 '10 at 18:01
source share
5 answers
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(YourObjectType)); YourObjectType yourObject = (YourObjectType)serializer.ReadObject(jsonStream); 

You can also use the JavaScriptSerializer , but the DataContractJsonSerializer supposedly better at handling complex types.

Oddly enough, the JavaScriptSerializer was once deprecated (in 3.5) and then resurrected due to ASP.NET MVC (in 3.5 SP1). That would be enough to shake confidence and lead me to use the DataContractJsonSerializer , as it is heavily baked for WCF.

+37
May 18 '10 at 18:10
source share

Just use the Json.NET library. This makes it easy to parse Json format strings:

 JObject o = JObject.Parse(@" { ""something"":""value"", ""jagged"": { ""someother"":""value2"" } }"); string something = (string)o["something"]; 

Documentation: Parsing a JSON Object Using JObject.Parse

+61
May 18 '10 at 18:10
source share

I think this is what you want:

 JavaScriptSerializer JSS = new JavaScriptSerializer(); T obj = JSS.Deserialize<T>(String); 
+18
May 18 '10 at 18:09
source share

You must create a structure representing the JSON keys (in case you know it for sure), and then you can easily deserialize the JSON string in your structure. In my example, I canceled the response description from the Google Cloud Message server:

 class templateResponse { public String multicast_id; public String success; public String failure; public String canonical_ids; public Result[] results; public class Result { public String message_id; public String registration_id; public String error; }; } 

Incoming JSON was:

 "\"multicast_id\":7400896764380883211,\"success\":1,\"failure\":0,\"canonical_ids\":0,\"results\":[{\"message_id\":\"0:1351777805148960%39895cf0f9fd7ecd\"}]}" 

So use

 templateResponse result = new JavaScriptSerializer().Deserialize<templateResponse>(json); 

and you get a deserialized result object

+5
Nov 02
source share

I would use the Json.NET library, which can convert the JSON response to an XML document. With an XML document, you can easily query XPath and extract the data you need. This is very useful to me.

+2
Jul 19 2018-11-11T00:
source share



All Articles