I have a requirement to add a 'type' property to every object I serialise using Json.Net. I understand Json.Net already supports this out of the box, but in my case, the type name needs to exclude the assembly, and the name of the property must be configurable (neither of which are supported).
I currently have this:
public class TypeConverter : JsonConverter
{
public override void WriteJson(JsonWriter writer, object value, JsonSerializer serialiser)
{
JObject jObject = JObject.FromObject(value, serializer);
jObject.AddFirst(new JProperty("myCustomTypePropertyName"), value.GetType().Name);
jObject.WriteTo(writer);
}
public override void ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serialiser)
{
throw new NotImplementedException();
}
public override bool CanConvert(Type objectType)
{
return objectType.IsClass;
}
}
This works for the outer type which is being serialised, but unfortunately the converter is not called for the nested objects. If I add the serialiser into the JObject.FromObject call then I get a self referencing loop exception as it tries to reenter the converter for the outer type.
The only way I can get around this is by manually reflecting and iterating over the properties at each level and serialising them using the serializer parameter, but it's super ugly, even before considering performance.
I would appreciate some help on this; I hope I'm missing something obvious.
(Note: I'm running .NET 3.5, so SerializationBinders are out of the question.)