Harry
Harry

Reputation: 1181

Gson parsing float as int

I incorrectly parsed a json field: "mileage":0.0" in my code into an int. It was parsed successfully until the value was 0.0. But as soon as the value of the json field changed from 0.0 to any other value, I started getting JsonFormatException. I'm using Gson to parse json in my application. So my question is why didn't the exception was not thrown when the value was 0.0 cause it was still float?

Upvotes: 0

Views: 943

Answers (1)

Ben P.
Ben P.

Reputation: 54214

Exactly how Gson works depends on how you were doing the deserialization. I'm going to bet that you were letting it do deserialization automatically, likely driven by the @SerializedName annotation. So let's assume you have some class with something like this in it:

@SerializedName("val")
private int myValue;

When Gson deserializes text into an instance of your object, it will "do its best" to give you what you want. This includes coercing some values from one type to another. For a class set up like the above, Gson will not only successfully coerce 0.0 into 0, it will also successfully coerce "1.0" (a String) into 1.

You will only get an Exception when the coercion is "impossible"; as soon as you have 0.1 or "1.5", Gson knows that it can't represent that value as an int and so it throws an exception.

Note that this works in both directions. If your json includes an integer number (e.g. {"val":3}) but your class declares private String myValue, Gson will successfully coerce the number to "3".

Upvotes: 2

Related Questions