简体   繁体   中英

Jackson parse Integer to Double

Environment: JACKSON 2.8.10 with Spring boot 1.5.10.RELEASE

In a JSON request I receive the following:

{
  total: 103
}

In other cases the total might be with decimal precision for example: 103.25 . I would like to be able to handle both cases using JACKSON

In my Java, I would like to read this 103 into a double as such:

Configuration conf = Configuration.builder().mappingProvider(new JacksonMappingProvider())
                .jsonProvider(new JacksonJsonProvider()).build();
Object rawJson = conf.jsonProvider().parse(payload);
double listPrice = JsonPath.read(rawJson, "$.total")

But then I receive the following error:

Java.lang.Integer cannot be cast to java.lang.Double.

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

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

This should do it.

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());
}

If you are going to do this repeatedly, create a method ...

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());
    }
}

The root cause of the exception is that the return type of JsonPath.read is an unconstrained type parameter. The compiler infers it to be whatever the call site expects, and adds a hidden typecast to ensure that the actual value returned has the expected type.

The problem arises when the JsonPath.read could actually return multiple types in a single call. The compiler has no way of knowing what could be returned ... or how to convert it.

Solution: take care of the conversion with some runtime type checking.


Here is another solution that should work:

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

... modulo that you will still get an ClassCastException if the value for "total" in the JSON is (say) a String.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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