Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Gson. Deserialize integers as integers and not as doubles

Tags:

java

json

gson

I have json object with arbitary values inside. And I want to deserialize it in a Map. Everything is ok except converting integers to a doubles. See example:

{"id":1, "inner_obj":{"key":"value","num":666,"map":{"key":"value"}}}

deserializes to this(map.toString()):

{id=1.0, inner_obj={key=value, num=666.0, map={key=value}}}

Is there some easy way to deserialize "id" and "num" as Integers and not as Doubles?

like image 442
Moses Avatar asked Jun 13 '13 15:06

Moses


People also ask

Why does Gson parse an integer as a double?

It sees all kind of numbers as a single type. That the numbers are parsed as a Double is an implementation detail of the Gson library. When it encounters a JSON number, it defaults to parsing it as a Double .

How can you prevent Gson from expressing integers as floats?

One option is to define a custom JsonDeserializer, however better would be to not use a HashMap (and definitely don't use Hashtable!) and instead give Gson more information about the type of data it's expecting. Show activity on this post. Show activity on this post. Show activity on this post.

Does Gson ignore extra fields?

3. Deserialize JSON With Extra Unknown Fields to Object. As you can see, Gson will ignore the unknown fields and simply match the fields that it's able to.

How do you serialize with Gson?

Serialization – Write JSON using Gson Serialization in the context of Gson means converting a Java object to its JSON representation. In order to do the serialization, we need to create the Gson object, which handles the conversion. Next, we need to call the function toJson() and pass the User object. Program output.


1 Answers

There are no integer type in JSON. 1 and 1.0 are the same. You need to parse that 1.0 to 1 in your code. Or you need to map the JSON to some VO class and define the type of fields of the class explicitly , so that GSON can understand what you are looking for.

like image 130
AllTooSir Avatar answered Oct 30 '22 07:10

AllTooSir