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);