I’m deserializing some properties to a Dictionary<string, object>.
When I deserialize some json, it populates the Dictionary with Int64 objects rather than Int32. I would like it to choose Int32 as the default well knowing that I could have javascript Numerics that would overflow on conversion. Throwing an exception in that case would be entirely acceptable.
Is there any way to achieve that? I’m hoping for some nice attributes or a convenient interface that could be implemented and added to the JsonSerializer. And I fear that I have to go deep down into the depths of Json.NET.
Basically I would like to have some way to control the known types for the objects so that I could get Int32‘s instead of Int64 and DateTimes instead of Strings.
As far as I know, there is no built-in way to do that.
There was an issue on this subject, but it has been closed.
Some comments from the author on the issue:
The easiest solution would of coure be to change the type to
Dictionary<string, int>, but I suppose you are not only reading numerics and thus are stuck withobject.Another option would be to either use Serialization Callbacks and manually convert those
Int64s toInt32or create your ownContract ResolverJsonConverter and directly control the (de-)serialization.Edit: I created a little example to be more specific.
Here is a very basic converter that only works with your specifc Dictionary:
You can either use attributes to decorate members with your converter or pass it as parameter to a (de-)serialize method. Here’s an example where I used an attribute:
And here’s the code I used to test the implementation:
Without the converter, the result would be:
and with the converter it is: