【发布时间】:2014-08-12 20:26:17
【问题描述】:
我正在使用 Gson 在我的 Android 应用程序中解析 JSON。假设我要解析这个 json:
{
"foo": 01
}
现在,根据 Json 规范 ECMA-404:
一个数字以 10 为底,没有多余的前导零 [...]
表示上面的json无效。不幸的是,Gson 出于某种原因没有实现这一点,并给我foo 作为String "01"。解析时,我无法判断原始值是字符串,还是格式错误的数字。
当我从foo 收到 JsonPrimitive 时,isString 方法返回 true。它应该抛出一个JsonSyntaxException。
我已经尝试过 gson 的自定义反序列化,但没有运气。我在网上到处搜索,甚至浏览了 Gson 的项目 open issues,但一无所获。
有没有办法检测这种类型的错误语法?
编辑
这是对我有用的代码:
private class Bar implements Serializable {
private static final long serialVersionUID = 1L;
@Expose
@SerializedName("foo")
private String foo;
}
public static void main(String[] args) throws Exception {
String json = "{\"foo\" : 01}";
Gson gson = new GsonBuilder().create();
Bar bar = gson.getAdapter(Bar.class).fromJson(json);
}
【问题讨论】:
-
如果您知道哪些 json 键的值是整数,那么最好将该值作为 int 获取。例如,JsonElement ele = obj.get("foo"); System.out.println(ele.getAsInt());将打印
'1'。是的,但一般来说,大多数时候您不希望专门针对某些字段进行这种额外检查。