Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Json.net serialize/deserialize derived types?

json.net (newtonsoft)
I am looking through the documentation but I can't find anything on this or the best way to do it.

public class Base {     public string Name; } public class Derived : Base {     public string Something; }  JsonConvert.Deserialize<List<Base>>(text); 

Now I have Derived objects in the serialized list. How do I deserialize the list and get back derived types?

like image 607
Will Avatar asked Dec 14 '11 23:12

Will


People also ask

What is the difference between serialize and deserialize JSON?

JSON is a format that encodes objects in a string. Serialization means to convert an object into that string, and deserialization is its inverse operation (convert string -> object). If you serialize this result it will generate a text with the structure and the record returned.

What is the difference between serialize and deserialize?

Serialization is a mechanism of converting the state of an object into a byte stream. Deserialization is the reverse process where the byte stream is used to recreate the actual Java object in memory. This mechanism is used to persist the object. The byte stream created is platform independent.

What does Jsonconvert Deserializeobject do?

Deserializes the JSON to the specified . NET type. Deserializes the JSON to the specified . NET type using a collection of JsonConverter.

What is Jsonconvert SerializeObject C#?

SerializeObject Method (Object, Type, JsonSerializerSettings) Serializes the specified object to a JSON string using a type, formatting and JsonSerializerSettings. Namespace: Newtonsoft.Json.


2 Answers

You have to enable Type Name Handling and pass that to the (de)serializer as a settings parameter.

Base object1 = new Base() { Name = "Object1" }; Derived object2 = new Derived() { Something = "Some other thing" }; List<Base> inheritanceList = new List<Base>() { object1, object2 };  JsonSerializerSettings settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All }; string Serialized = JsonConvert.SerializeObject(inheritanceList, settings); List<Base> deserializedList = JsonConvert.DeserializeObject<List<Base>>(Serialized, settings); 

This will result in correct deserialization of derived classes. A drawback to it is that it will name all the objects you are using, as such it will name the list you are putting the objects in.

like image 150
Madmenyo Avatar answered Sep 18 '22 14:09

Madmenyo


If you are storing the type in your text (as you should be in this scenario), you can use the JsonSerializerSettings.

See: how to deserialize JSON into IEnumerable<BaseType> with Newtonsoft JSON.NET

Be careful, though. Using anything other than TypeNameHandling = TypeNameHandling.None could open yourself up to a security vulnerability.

like image 29
kamranicus Avatar answered Sep 18 '22 14:09

kamranicus