Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to deserialize a JObject to .NET object

I happily use the Newtonsoft JSON library. For example, I would create a JObject from a .NET object, in this case an instance of Exception (might or might not be a subclass)

if (result is Exception)     var jobjectInstance = JObject.FromObject(result); 

now I know the library can deserialize JSON text (i.e. a string) to an object

// only works for text (string) Exception exception = JsonConvert.DeserializeObject<Exception>(jsontext);  

but what I am looking for is:

// now i do already have an JObject instance Exception exception = jobjectInstance.???? 

Well it is clear that I can go from on JObject back to JSON text and then use the deserialize functionality, but that seems backwards to me.

like image 434
Sebastian Avatar asked Dec 14 '10 16:12

Sebastian


People also ask

How do I deserialize JSON data?

A common way to deserialize JSON is to first create a class with properties and fields that represent one or more of the JSON properties. Then, to deserialize from a string or a file, call the JsonSerializer. Deserialize method.

How do you serialize and deserialize an object in C# using JSON?

It returns JSON data in string format. In Deserialization, it does the opposite of Serialization which means it converts JSON string to custom . Net object. In the following code, it calls the static method DeserializeObject() of the JsonConvert class by passing JSON data.


2 Answers

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

like image 120
Tien Do Avatar answered Nov 24 '22 08:11

Tien Do


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.

like image 33
Sebastian Avatar answered Nov 24 '22 08:11

Sebastian