Serializing and Deserializing by a base class

Jun 25, 2012 at 10:13 PM

Is it possible to serialize an object and include type information if it is not of the specific base type?

An example

 

public class A {
	public string Name;
}
public class B : A {
	public int Age;
}

 

Here we have a base class and a subclass.

If I where to serialize an instance

var a = new A { Name = "A" };
var b = new B { Name = "B", Age = 10 };

Console.WriteLine(JsonConvert.SerializeObject(a));
//writes {"Name":"A"}
Console.WriteLine(JsonConvert.SerializeObject(b));
//writes {"Age":10,"Name":"B"}

We get the result above. I can use JsonSettings and setting TypeNameHandling to Objects  and get type information.

{"$type":"MyProj.B, MyProj","Age":10,"Name":"B"}

In this case I don't want to have type info on all objects (I like the Auto handling) but when I serialize/deserialize a subclass I would like the type attribute populated in the json object.

Suggestion

JsonConvert.SerializeObject<A>(a);
//should generate {"Name":"A"}

JsonConvert.SerializeObject<A>(b);
//should generate {"$type":"MyProj.B, MyProj","Name":"B", "Age":10}

Both of these should then be deserialized using

JsonConvert.DeserializeObject<A>(json)
And return a instance of an A or B class based on the type information.

Is this already possible today by using some other way?

/Dan