有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

javajackson将整数解析为双精度

环境:JACKSON 2.8.10Spring 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) 个答案

  1. # 1 楼答案

    Is there a way to handle the case above without doing string/mathematical manipulations?

    这应该可以做到

    Configuration conf = Configuration.builder()
           .mappingProvider(new JacksonMappingProvider())
           .jsonProvider(new JacksonJsonProvider())
           .build();
    Object rawJson = conf.jsonProvider().parse(payload);
    Object rawListPrice = JsonPath.read(rawJson, "$.total");
    double listPrice;
    if (rawListPrice instanceOf Double) {
        listPrice = (Double) rawListPrice;
    } else if (rawListPrice instanceOf Integer) {
        listPrice = (Integer) rawListPrice;
    } else {
        throw new MyRuntimeException("unexpected type: " + rawListPrice.getClass());
    }
    

    如果要重复执行此操作,请创建一个方法

    public double toDouble(Object number) {
        if (number instanceof Double) {
            return (Double) number;
        } else if (number instanceof Integer) {
            return (Integer) number;
        } else {
            throw new MyRuntimeException("unexpected type: " + number.getClass());
        }
    }
    

    异常的根本原因是JsonPath.read的返回类型是一个不受约束的类型参数。编译器推断它是调用站点所期望的类型,并添加一个隐藏类型转换以确保返回的实际值具有所期望的类型

    JsonPath.read实际上可以在一个调用中返回多个类型时,问题就出现了。编译器无法知道可以返回什么。。。或者如何转换它

    解决方案:通过一些运行时类型检查来处理转换


    以下是另一个可行的解决方案:

    double listPrice = ((Number) JsonPath.read(rawJson, "$.total")).doubleValue();
    

    。。。如果JSON中“total”的值是(比如)字符串,那么仍然会得到一个ClassCastException