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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With