0

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.

SørenHN
  • 566
  • 5
  • 20
  • 1
    Yes it is, use a [custom converter](https://www.newtonsoft.com/json/help/html/CustomJsonConverter.htm) – Liam Sep 03 '21 at 10:41
  • Yes, that is a solution, but then i would again have to manually specify that I want to use this converter each time that I have to serialize a `ValueContainer` object. Is there a way to specify it ones, and then not have to deal it again? – SørenHN Sep 03 '21 at 10:50
  • @SørenHN it is the same as specifying `TypeNameHandling` - use `JsonPropertyAttribute`. – Guru Stron Sep 03 '21 at 10:54
  • That very much depends on how your using Json.Net. You can often specify a default converter in things like web api. But you don't actually specify how your using Json.Net so I can't answer that question – Liam Sep 03 '21 at 10:56
  • Seems [you can't override it "globally"](https://stackoverflow.com/questions/5881028/can-you-extend-the-default-jsonconverter-used-in-json-net-for-collections) – Liam Sep 03 '21 at 10:58
  • Does this answer your question? [How to implement custom JsonConverter in JSON.NET?](https://stackoverflow.com/questions/8030538/how-to-implement-custom-jsonconverter-in-json-net) – Liam Sep 03 '21 at 11:01

1 Answers1

1

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}}
Guru Stron
  • 102,774
  • 10
  • 95
  • 132