Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make Newtonsoft JsonConvert Default to Int32 Rather Than Int64

Tags:

c#

I am converting Json to ExpandoObject by doing this

JsonConvert.DeserializeObject<ExpandoObject>(jsonText)

The integer I got was Int64 but I prefer Int32.

Is there any settings in JsonConvert that I can use to change the default behavior?

like image 438
acai Avatar asked Feb 04 '23 11:02

acai


1 Answers

Quoting a post by James Newton King (maker of Newtonsoft.JSON) in this thread:

Json.NET by default reads integer values as Int64 because there is no way to know whether the value should be Int32 or Int64, and Int64 is less likely to overflow. For a typed property the deserializer knows to convert the Int64 to a Int32 but because your property is untyped you are getting an Int64.

This sort of question has been asked on SO before. Basically it comes down to: you need to create a custom converter. If not for your object, then for integers.

For reference regarding that, see this answer by user drzaus who tackled exactly this issue, as well as this one by enzi, who goes into more detail.

like image 63
stelioslogothetis Avatar answered Feb 20 '23 16:02

stelioslogothetis