Newtonsoft JSON Deserialize

My JSON looks like this:

{"t":"1339886","a":true,"data":[],"Type":[['Ants','Biz','Tro']]} 

I found the Newtonsoft JSON.NET deserialization library for C #. I tried using it as follows:

 object JsonDe = JsonConvert.DeserializeObject(Json); 

How can I access the JsonDe object to get all the Type data? I tried it with a loop, but it does not work because the object does not have a counter.

+63
c # deserialization
Jun 11 '13 at 7:36
source share
3 answers

You can implement a class that contains the fields you have in JSON

 class MyData { public string t; public bool a; public object[] data; public string[][] type; } 

and then use the generic version of DeserializeObject:

 MyData tmp = JsonConvert.DeserializeObject<MyData>(json); foreach (string typeStr in tmp.type[0]) { // Do something with typeStr } 

Documentation: Serializing and Deserializing JSON

+103
Jun 11 '13 at 7:41
source share

A simpler solution: using a dynamic type

As with Json.NET 4.0 Release 1, there is built-in dynamic support. You do not need to declare a class, just use dynamic :

 dynamic jsonDe = JsonConvert.DeserializeObject(json); 

All fields will be available:

 foreach (string typeStr in jsonDe.Type[0]) { // Do something with typeStr } string t = jsonDe.t; bool a = jsonDe.a; object[] data = jsonDe.data; string[][] type = jsonDe.Type; 

With dynamic, you do not need to create a specific class to store your data.

+61
Apr 08 '14 at 15:07
source share

According to the Newtonsoft Documentation, you can also deserialize an anonymous object as follows:

 var definition = new { Name = "" }; string json1 = @"{'Name':'James'}"; var customer1 = JsonConvert.DeserializeAnonymousType(json1, definition); Console.WriteLine(customer1.Name); // James 
+2
Oct 22 '15 at 15:22
source share



All Articles