When creating a custom Json Converter one of the methods which needs to be overridden is:
public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
What is "existingValue" parameter used for? What does the variable name "existingValue" mean in this context?
Simply put, the existingValue
parameter gives you the existing or default value of the object that will ultimately be replaced with the value returned from the ReadJson
method. This gives the ReadJson
method the chance to evaluate the existing value when determining what to return. The method could, for example, decide to keep the default, or combine it in some way with the deserialized value from the reader if desired.
Consider the following example. This converter will deserialize an integer value from the JSON and return the sum of that value and the existing value for the field being deserialized to.
class AdditiveIntConverter : JsonConverter { public override bool CanConvert(Type objectType) { return (objectType == typeof(int)); } public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer) { JToken token = JToken.Load(reader); return (int)existingValue + token.ToObject<int>(); } public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) { throw new NotImplementedException(); } }
Now let's say we have a class Foo
which has two int
properties, Value1
and Value2
, both of which use this converter. Value1
is assigned a default value of 42
in the constructor, while Value2
has the usual default value of zero.
class Foo { [JsonConverter(typeof(AdditiveIntConverter))] public int Value1 { get; set; } [JsonConverter(typeof(AdditiveIntConverter))] public int Value2 { get; set; } public Foo() { Value1 = 42; } }
If we deserialize some data into this class...
class Program { static void Main(string[] args) { string json = @"{ ""Value1"" : 18, ""Value2"" : 33 }"; Foo foo = JsonConvert.DeserializeObject<Foo>(json); Console.WriteLine("Value1: " + foo.Value1); Console.WriteLine("Value2: " + foo.Value2); } }
...we get the following result:
Value1: 60 Value2: 33
Of course, this is just a contrived example. In practice, there is not much of a need to use the existingValue
parameter when implementing a JsonConverter, and most of the time its value will be either null or zero. You can safely ignore it.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With