json - How to deserialize a JObject to .NET object

ID : 10216

viewed : 56

Tags : .netjsonexceptionserializationjson.net.net

Top 4 Answer for json - How to deserialize a JObject to .NET object

vote vote

94

According to this post, it's much better now:

// pick out one album JObject jalbum = albums[0] as JObject;  // Copy to a static Album instance Album album = jalbum.ToObject<Album>(); 

Documentation: Convert JSON to a Type

vote vote

90

From the documentation, I found this:

JObject o = new JObject(    new JProperty("Name", "John Smith"),    new JProperty("BirthDate", new DateTime(1983, 3, 20)) );  JsonSerializer serializer = new JsonSerializer(); Person p = (Person)serializer.Deserialize(new JTokenReader(o), typeof(Person));  Console.WriteLine(p.Name); 

The class definition for Person should be compatible to the following:

class Person {     public string Name { get; internal set; }     public DateTime BirthDate { get; internal set; } } 

If you are using a recent version of JSON.net and don't need custom serialization, please see Tien Do's answer, which is more concise.

vote vote

78

Too late, just in case some one is looking for another way:

void Main() {     string jsonString = @"{   'Stores': [     'Lambton Quay',     'Willis Street'   ],   'Manufacturers': [     {       'Name': 'Acme Co',       'Products': [         {           'Name': 'Anvil',           'Price': 50         }       ]     },     {       'Name': 'Contoso',       'Products': [         {           'Name': 'Elbow Grease',           'Price': 99.95         },         {           'Name': 'Headlight Fluid',           'Price': 4         }       ]     }   ] }";      Product product = new Product();     //Serializing to Object     Product obj = JObject.Parse(jsonString).SelectToken("$.Manufacturers[?(@.Name == 'Acme Co' && @.Name != 'Contoso')]").ToObject<Product>();      Console.WriteLine(obj); }   public class Product {     public string Name { get; set; }     public decimal Price { get; set; } } 
vote vote

63

Top 3 video Explaining json - How to deserialize a JObject to .NET object

Related QUESTION?