Open 6e06d03f opened 1 year ago
public class NullToNumberConverter<T> : JsonConverter<T?> { public override T? ReadJson(JsonReader reader, Type objectType, T? existingValue, bool hasExistingValue, JsonSerializer serializer) { throw new NotImplementedException(); } public override void WriteJson(JsonWriter writer, T? value, JsonSerializer serializer) { writer.WriteValue(value == null ? 0 : 1); } } public class TestClass { [JsonProperty("name")] [JsonConverter(typeof(NullToNumberConverter<string>))] public string? Name{ get; set; } } public class Program { static void Main(string[] args) { var obj = new TestClass(); string json = JsonConvert.SerializeObject(obj); Console.WriteLine(json); } }
{"name":0}
{"name":null}
I've found out why this is happening.
JsonSerializerInternalWriter.cs
private void SerializeValue(JsonWriter writer, object? value, JsonContract? valueContract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerProperty) { if (value == null) { writer.WriteNull(); return; } JsonConverter jsonConverter = member?.Converter ?? containerProperty?.ItemConverter ?? containerContract?.ItemConverter ?? valueContract!.Converter ?? Serializer.GetMatchingConverter(valueContract!.UnderlyingType) ?? valueContract!.InternalConverter; if (jsonConverter != null && jsonConverter.CanWrite) { SerializeConvertable(writer, jsonConverter, value, valueContract, containerContract, containerProperty); return; } .....
Can we change like this??
private void SerializeValue(JsonWriter writer, object? value, JsonContract? valueContract, JsonProperty? member, JsonContainerContract? containerContract, JsonProperty? containerProperty) { JsonConverter jsonConverter = member?.Converter ?? containerProperty?.ItemConverter ?? containerContract?.ItemConverter ?? valueContract!.Converter ?? Serializer.GetMatchingConverter(valueContract!.UnderlyingType) ?? valueContract!.InternalConverter; if (value == null && jsonConverter == null && !jsonConverter.CanWrite) { writer.WriteNull(); return; } if (jsonConverter != null && jsonConverter.CanWrite) { SerializeConvertable(writer, jsonConverter, value, valueContract, containerContract, containerProperty); return; } .....
Steps to reproduce
Expected behavior
Actual behavior
Note
I've found out why this is happening.
JsonSerializerInternalWriter.cs
Can we change like this??