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?
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 .
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.
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With