Open btshft opened 6 years ago
This is still an issue for me with .NET Framework 4.8 & version 12.0.3
I found an example of the issue written by someone else: https://dotnetfiddle.net/5PLvsk
I believe the Json library to write the values calls if(value == null){writeNullValue(value);} before it picks up the custom converter. Unless Netwonsoft has changed that recently your custom converter will never write a null value. I worked around this by creating a custom resolver and overriding the IValueProvider methods and set "default" custom values there.
Things may have changed or i may be missing something but as far as I can see that is the issue and the way around it.
I figure this is still not supported?
In System.Text.Json JsonConverter
has an overrible bool HandleNull
property which allows this behaviour. I can't find a similar thing on Newtonsoft.
A workaround would be to write a converter for the class containing the property, but it is quite long.
Workaround is to create new data type which will be wrapper over original data and in WriteJson handle the case when inner value is null
Intro
Area: Converters, Serialization Issue: Methods
JsonConverter.CanConvert
andJsonConverter.WriteJson
are not called during serialization if source value isnull
. Description: I need to convert the C# object to JSON string in such way that for everyDateTime
property of source object the result JSON will contain a duplicate property with name of source property plus suffix 'Msk' and it will contain a Moscow DateTime. If the source property value is null, then I want the resulting value to be null too. However now if the value is null the methodsCanConvert
andWriteJson
are not called, and accordingly the new property is not created in result JSON. Library version: 11.0.1 Platform: .NET Core 2.1.4 (also reproduced at .NET Framework 4.6.1)Source type model
JsonConverter
Serialization
Actual JSON after serialization
Expected JSON after serialization