-
Notifications
You must be signed in to change notification settings - Fork 3.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Nullable DateTime in Dictionary can't use custom converter to convert into empty string #2945
Comments
The behavior you see is pretty much hard-coded: Newtonsoft.Json/Src/Newtonsoft.Json/Serialization/JsonSerializerInternalWriter.cs Lines 154 to 160 in 2eaa475
As a (past) user of the library myself (only still using it in old legacy projects i didn't migrate to modern .NET), i have to admit that i can't muster much hope for this situation to be improved. That said, feel free to look at Newtonsoft.Json's development activities over the last few years and form your own opinion about it. A work-around for this limitation is to write a converter that deals with the dictionary itself -- this way, this dictionary converter would then be able to iterate over the dictionary, deal with Nullable<T> values itself directly (thus bypassing hard-coded null checks in the serializer) and write/serialize the dictionary data to the JsonWriter in whatever way you need. If you feel this being too much work or your real situation is more complex and involving not just dictionaries with values from a limited number of relatively simple types, i would strongly suggest you contemplate switching to STJ if there are no roadblocks preventing you from doing that... |
For some reasons, can't switch back to STJ :( |
That's unfortunate :-( because this would be easy-peasy to do in STJ https://dotnetfiddle.net/RDmNxD |
I have some classes must be stored in a dictionary, but the code can not be uploaded, so I simplify the code and change it to below acts like the actual behavior.
But the Nullable<DateTime> can not trigger the converter and can't be serialize into an empty string, always serialize into null value, but actually I need it is an empty string so the front-end can accept it (front-end is a third-party library that can not be changed and some fields must have unless an empty string than null )
Source/destination types
JsonConvertTestClass Code ( have tried using [JsonConverter] attribute in DateTime? field ):
Custom Converter Code (no matter use JsonConverter or JsonConverter<DateTime?>):
Serialization Code:
Source/destination JSON
Expected behavior
Actual behavior
All DateTime are null
Steps to reproduce
The text was updated successfully, but these errors were encountered: