There is no functionality in Json.NET to do this out of the box, but you can do this with custom contract resolution :
[AttributeUsage(AttributeTargets.Class| AttributeTargets.Interface, AllowMultiple = false, Inherited = false)]
public class AddJsonTypenameAttribute : System.Attribute
{
}
public class AddJsonTypenameContractResolver : DefaultContractResolver
{
static AddJsonTypenameContractResolver instance;
static AddJsonTypenameContractResolver() { instance = new AddJsonTypenameContractResolver(); }
public static AddJsonTypenameContractResolver Instance { get { return instance; } }
protected override JsonProperty CreateProperty(MemberInfo member, MemberSerialization memberSerialization)
{
return base.CreateProperty(member, memberSerialization)
.ApplyAddTypenameAttribute();
}
protected override JsonArrayContract CreateArrayContract(Type objectType)
{
return base.CreateArrayContract(objectType)
.ApplyAddTypenameAttribute();
}
}
public static class ContractResolverExtensions
{
public static JsonProperty ApplyAddTypenameAttribute(this JsonProperty jsonProperty)
{
if (jsonProperty.TypeNameHandling == null)
{
if (jsonProperty.PropertyType.GetCustomAttribute<AddJsonTypenameAttribute>(false) != null)
{
jsonProperty.TypeNameHandling = TypeNameHandling.All;
}
}
return jsonProperty;
}
public static JsonArrayContract ApplyAddTypenameAttribute(this JsonArrayContract contract)
{
if (contract.ItemTypeNameHandling == null)
{
if (contract.CollectionItemType.GetCustomAttribute<AddJsonTypenameAttribute>(false) != null)
{
contract.ItemTypeNameHandling = TypeNameHandling.All;
}
}
return contract;
}
}
Then apply it to your interfaces or base types as follows:
[AddJsonTypename]
public interface IAnimal
{
bool CanFly { get; }
}
[AddJsonTypename]
public abstract class Animal : IAnimal
{
public bool CanFly { get; set; }
}
, Inherited = false
. , List<Animal>
, List<FlyingAnimal>
. , . , ., , .
, -API, ., , Web API 2: JSON camelCased, -. Newtonsoft:
TypeNameHandling , JSON . SerializationBinder , None.
, , . TypeNameHandling Newtonsoft Json, Json.NET -API, blackhat https://www.blackhat.com/docs/us-17/thursday/us-17-Munoz-Friday-The-13th-JSON-Attacks-wp.pdf.