I need to apply a custom converter conditionally based on the depth of the reader. The root of the json object is a Def
class that should deserialize like normal, however any Def
s within the object should be resolved to a reference to that deserialized Def
. My plan is to check the depth of the reader, and if we're not at the root, then create a skeleton Def
and add it to a list to be resolved later once we've deserialized all the Def
s.
public class DefConverter : JsonConverter {
public override bool CanConvert(Type objectType) {
return objectType == typeof(Def);
}
public override object? ReadJson(JsonReader reader, Type objectType, object? existingValue, JsonSerializer serializer) {
if (reader.Depth == 0) {
// Use the default serializer to read the Def
return serializer.Deserialize(reader, objectType); // ?
}
// Create skeleton Def with id
// Add to list of defs to be resolved later
}
public override bool CanWrite => false;
public override void WriteJson(JsonWriter writer, object? value, JsonSerializer serializer) {
throw new NotImplementedException();
}
}
The issue I'm running into is that there doesn't seem to be a way to call the Json.NET default converter, using serializer.Deserialize(reader, objectType)
will just cause an infinite loop as it just calls the custom converter.