SørenHN
SørenHN

Reputation: 696

How to automatically include type information when serializing?

Is it possible to specify that I always want type-information in the json object when serializing a property in an class? (Ideally with Newtonsoft). I'm thinking something like this:

public abstract class Value {...}
public class BigValue : Value {...}
public class SmallValue : Value {...}

public class ValueContainer
{
    [JsonSetting(TypenameHandling = TypenameHandling.All)] // <--- Something like this?
    public Value TheValue { get; set; }
}

I am aware that I could specify this behavior when doing the parsing with a custom converter. But I want to include the typeinformation every time objects of this type is serialized, without manually having to specify which serialization options to use.

Upvotes: 1

Views: 695

Answers (1)

Guru Stron
Guru Stron

Reputation: 141575

Newtonsoft.Json's JsonPropertyAttribute has TypeNameHandling property which you can set:

public class Root
{
    [JsonProperty(TypeNameHandling = TypeNameHandling.All)]
    public Base Prop { get; set; }
}
public class Base
{
    public int IntProp { get; set; }
}
public class Child:Base
{
}

// Example:
var result = JsonConvert.SerializeObject(new Root
{
    Prop = new Child()
});
Console.WriteLine(result);  // prints {"Prop":{"$type":"SOAnswers.TestTypeNamehandling+Child, SOAnswers","IntProp":0}}

Upvotes: 1

Related Questions