javajackson将整数解析为双精度
环境:JACKSON 2.8.10
与Spring boot 1.5.10.RELEASE
在JSON请求中,我收到以下信息:
{
total: 103
}
在其他情况下total
可能具有十进制精度,例如:103.25
。我希望能够使用JACKSON
处理这两种情况
在我的Java中,我想把这个103读入一个double
中,如下所示:
Configuration conf = Configuration.builder().mappingProvider(new JacksonMappingProvider())
.jsonProvider(new JacksonJsonProvider()).build();
Object rawJson = conf.jsonProvider().parse(payload);
double listPrice = JsonPath.read(rawJson, "$.total")
但随后我收到以下错误:
Java.lang.Integer cannot be cast to java.lang.Double.
有没有一种方法可以在不进行字符串/数学运算的情况下处理上述情况
# 1 楼答案
这应该可以做到
如果要重复执行此操作,请创建一个方法
异常的根本原因是
JsonPath.read
的返回类型是一个不受约束的类型参数。编译器推断它是调用站点所期望的类型,并添加一个隐藏类型转换以确保返回的实际值具有所期望的类型当
JsonPath.read
实际上可以在一个调用中返回多个类型时,问题就出现了。编译器无法知道可以返回什么。。。或者如何转换它解决方案:通过一些运行时类型检查来处理转换
以下是另一个可行的解决方案:
。。。如果JSON中“total”的值是(比如)字符串,那么仍然会得到一个
ClassCastException