简体   繁体   English

Gson将float解析为int

[英]Gson parsing float as int

我错误地将代码中的json字段: "mileage":0.0"解析为一个int 。它被成功解析,直到值为0.0 。但是,一旦json字段的值从0.0更改为任何其他值,我就开始越来越JsonFormatException我使用GSON在我的应用程序解析JSON。所以我的问题是为什么没有异常没有被当值抛出0.0的原因,它仍然漂浮?

Exactly how Gson works depends on how you were doing the deserialization. Gson的确切工作方式取决于您进行反序列化的方式。 I'm going to bet that you were letting it do deserialization automatically, likely driven by the @SerializedName annotation. 我敢打赌,您让它自动进行反序列化,可能是由@SerializedName注释驱动的。 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. 当Gson将文本反序列化为对象的实例时,它将“尽最大努力”为您提供所需的内容。 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 . 对于上述设置的类,Gson不仅将成功将0.0强制转换为0 ,还将成功将"1.0" (字符串)强制转换为1

You will only get an Exception when the coercion is "impossible"; 当强制是“不可能的”时,您只会得到一个Exception 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. 一旦您拥有0.1"1.5" ,Gson就会知道它不能将该值表示为int ,因此会引发异常。

Note that this works in both directions. 请注意,这在两个方向上均有效。 If your json includes an integer number (eg {"val":3} ) but your class declares private String myValue , Gson will successfully coerce the number to "3" . 如果您的json包含整数(例如{"val":3} ),但您的类声明了private String myValue ,则Gson将成功将数字强制为"3"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM