4

I'm using the NewtonSoft JSON.NET library for serializing the following class where DTOBase can hold derived instances.

public class Command { public DTOBase CommandDTO { get; set; } } 

Per this article you need to include the JsonProperty attribute so that the derived instances get deserialized properly

public class Command { [JsonProperty(TypeNameHandling = TypeNameHandling.All)] public DTOBase CommandDTO { get; set; } } 

The question is whether there is any other way besides using an attribute to get the same result? I would prefer to not be coupled to the NewtonSoft library and json serialization in particular at the class level. Is there a way to specify some settings on the Serialize/Deserialize methods of the library at all to get the same result?

1 Answer 1

4

The TypeNameHandling property can be set on JsonSerializerSettings when you call JsonConvert.SerializeObject(value, settings).

If you only want the name included for derived objects set TypeNameHandling to TypeNameHandling.Auto.

Sign up to request clarification or add additional context in comments.

2 Comments

Hi James, I tried this but it did not work, the serialized string does not contain the type information for the property like it does when I use the JsonProperty attribute. v var settings = new JsonSerializerSettings { TypeNameHandling = TypeNameHandling.All}; string serializedInstance = JsonConvert.SerializeObject(myobject,Formatting.None,settings);
Looks like I had an older version of te library. I upgraded to the latest one and the JsonSerializerSettings with TypeNameHandling.Auto works as expected.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.