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开发者_JAVA技巧 the library at all to get the same result?
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
.
精彩评论