Reputation: 3879
I've been trying to deserialize some null
paramaters with JsonSerializer
and a custom JsonConverter
from examples from posts I've seen about the subject, but its not working.
When I debug the NullToEmptyStringConverter
is seems to be skipping the null parameter Version
which I have deliberately set to null
and just returning the string
values that have a value. Then when you debug the deserialized object it is Version = null
still.
public class NullToEmptyStringConverter : JsonConverter<string> {
public override bool CanConvert(Type typeToConvert) {
return typeToConvert == typeof(string);
}
public override string Read(ref Utf8JsonReader reader, Type typeToConvert, JsonSerializerOptions options) {
string value = reader.GetString();
if(value == null) {
value = "";
}
return value;
}
public override void Write(Utf8JsonWriter writer, string value, JsonSerializerOptions options) {
throw new NotImplementedException();
}
}
I have added it to JsonSerializeOptions
and added the attribute. Another thing I am confused about is why is the Read
method being invoked for every parameter even though I have placed it above the Version
property?
public class Application {
[JsonPropertyName("version")]
[JsonConverter(typeof(NullToEmptyStringConverter))]
public string Version { get; set; }
[JsonPropertyName("name")]
public string Name { get; set; }
[JsonPropertyName("description")]
public string Description { get; set; }
}
Adding to the Converter
var options = new JsonSerializerOptions();
options.Converters.Add(new NullToEmptyStringConverter());
var config = JsonSerializer.Deserialize<ConfigRoot>(responseData.ToString(), options);
Upvotes: 3
Views: 2069
Reputation: 93303
When I debug the
NullToEmptyStringConverter
is seems to be skipping the null parameterVersion
...
JsonConverter<T>
includes a virtual property named HandleNull
, which is false
by default. Because of this, NullToEmptyStringConverter
isn't used for null
values. Override the getter and set it to return true
, like this:
public override bool HandleNull => true;
...why is the Read method being invoked for every parameter even though I have placed it above the Version property?
In your example, you have the following line:
options.Converters.Add(new NullToEmptyStringConverter());
This registers NullToEmptyStringConverter
as a global converter. Remove this registration and the converter will run only for the Version
property, due to the [JsonConverter]
attribute.
Upvotes: 4