We're using Web API with Json.Net using TypeNameHandling = TypeNameHandling.Objects
in our serializer settings. This works fine, but we use the type information only client-side, never for deserialization. Our serialized objects look like this:
{
"$type": "PROJECTNAME.Api.Models.Directory.DtoName, PROJECTNAME.Api",
"id": 67,
"offices": [{
"$type": "PROJECTNAME.Api.Models.Directory.AnotherDtoName, PROJECTNAME.Api",
"officeName": "FOO"
}]
},
I would like to customize the value in the $type
property so it reads as:
{
"$type": "Models.Directory.DtoName",
"id": 67,
"offices": [{
"$type": "Models.Directory.AnotherDtoName",
"officeName": "FOO"
}]
},
I already have a contract resolver that inherits from CamelCasePropertyNamesContractResolver
. I figure what I need to do is turn off TypeNameHandling
and add a custom property myself. I'm 95% there:
protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization)
{
var assemblyName = type.Assembly.GetName().Name;
var typeName = type.FullName.Substring(assemblyName.Length + 1);
var typeProperty = new JsonProperty()
{
PropertyName = "$type",
PropertyType = typeof(string),
Readable = true,
Writable = true,
ValueProvider = null // ????? typeName
};
var retval = base.CreateProperties(type, memberSerialization);
retval.Add(typeProperty);
return retval;
}
At this point I'm stuck with supplying the property's value.
I'm unsure that this is the correct approach because each of the ValueProvider
types from Json.Net take a MemberInfo
as a constructor parameter. I don't have a MemberInfo
to supply as a parameter, so.... I'm stuck.
How do I add a custom $type
value? Since I'm not doing deserialization in C# I will never need to convert the type information back into a type.