Kristof Daems
Kristof Daems

Reputation: 91

JsonConverter resolve reference

I have a custom JsonConverter which handles the creation of derived types during deserialization, in most cases this works as expected. The situation where I have an issue is, when there are referenced objects in the json structure. Is it possible to rely on the default deserialization when we detect a reference? What should the ReadJson method return? In the sample below we return null in case of a reference.

if (reader.TokenType == JsonToken.Null) return null;

var jObject = JObject.Load(reader);
JToken token;
if (jObject.TryGetValue("$ref", out token))
{
   return null; 
}

Or must we implement a custom ReferenceResolver as the default one can't be used in the converter (only internal use)?

Any suggestions are welcome.

Upvotes: 3

Views: 726

Answers (1)

Kristof Daems
Kristof Daems

Reputation: 91

After some extra testing, I found the solution myself. When I first was trying using the default ReferenceResolver I got an exception saying "The DefaultReferenceResolver can only be used internally.". This pointed my in the wrong direction, you can use the DefaultReferenceResolver in your converter but I was calling it the wrong way...

Solution:

public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
{
  if (reader.TokenType == JsonToken.Null) return null;
  var jObject = JObject.Load(reader);
  string id = (string)jObject["$ref"];
  if (id != null)
  {
    return serializer.ReferenceResolver.ResolveReference(serializer, id);
  }
  // Custom instance creation comes here
}

Upvotes: 6

Related Questions