0

Json.Net has support for controlling custom serialization using derived versions of JsonConverter. These enable a developer to control how serialization for a particular type occurs. There are a few ways a JsonConverter can be associated with a type or field including such as using a [JsonConverter] attribute on the member or type.

However these are only called if using JsonConvert.DeserializeObject or JsonConvert.SerializeObject for deserializing to new instances of objects or serializing existing objects. If you need to patch or update an existing object, JsonConverter.Populate is what is referred to to use, but does not use converters. Instead, it relies solely on reflection and naive object creation which blows up if you implement polymorphic serialization and/or use abstract classes or interfaces.

if(_value == null)
{
    _value = JsonConvert.DeserializeObject<T>(jsonContent, WebConstants.JSON_SERIALIZER_SETTINGS);
}
else
{
    JsonConvert.PopulateObject(jsonContent, _value, WebConstants.JSON_SERIALIZER_SETTINGS);
}

My question is; what can you do in this case to control custom serialization when patching existing objects in Json.Net? Ideally I would like to reuse the logic from the custom JsonConverter implementations so that I am not implementing this logic twice.

StampyTurtle
  • 2,728
  • 2
  • 14
  • 16
  • [`JsonConverter.ReadJson(JsonReader, Type, Object existingValue, JsonSerializer)`](https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_JsonConverter_ReadJson.htm) has the `existingValue` argument so you can just call the converter directly and pass in `_value`. Of course the converter must be written correctly to populate the `existingValue` rather than ignore it -- and many aren't. – dbc Jun 16 '21 at 16:59
  • 1
    Examples of converters using the `existingValue` can be found [here](https://stackoverflow.com/a/39267164/3744182) or [here](https://stackoverflow.com/a/35590069/3744182) or [here](https://stackoverflow.com/a/34638748/3744182). – dbc Jun 16 '21 at 16:59
  • Does that answer your question? If not, what additional help do you need? – dbc Jun 17 '21 at 00:07

0 Answers0