Jayway JsonPath read long Java

2019-07-18 12:10发布

In JSON i receive a unix timestamp:

{
  "order": {
    "date": 1531380888
  }
}

I want to read this value into a long so I can create a Date object out of it:

Configuration conf = Configuration.builder().mappingProvider(new JacksonMappingProvider())
    .jsonProvider(new JacksonJsonProvider()).build();
Object rawJson = conf.jsonProvider().parse(payload);
Long orderDate = JsonPath.read(rawJson, "$.order.date");

But JSONPath insists that this Integer cannot be cast to long:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long

Is there a way to read Long with Jsonpath, or automagically convert this unix timestamp to Java date object?

The imports:

import com.jayway.jsonpath.Configuration;
import com.jayway.jsonpath.JsonPath;
import com.jayway.jsonpath.spi.json.JacksonJsonProvider;
import com.jayway.jsonpath.spi.mapper.JacksonMappingProvider;

Problem with Integer: max value is 2147483647, which is Tuesday, January 19, 2038 3:14:07 AM GMT. Can't use Integer for unix timestamp. Thanks.

1条回答
时光不老,我们不散
2楼-- · 2019-07-18 12:58

You could configure the ObjectMapper used by JsonPath to treat integers as longs. This will ensure that all integer values (and long values) are returned as longs.

Here's an example:

String payload = "{\"order\": { \"date\": 1531380888 } }";

ObjectMapper objectMapper = new ObjectMapper().configure(DeserializationFeature.USE_LONG_FOR_INTS, true);

Configuration conf = Configuration.builder()
    .jsonProvider(new JacksonJsonProvider(objectMapper))
    .build();
Object rawJson = conf.jsonProvider().parse(payload);
Long orderDate = JsonPath.read(rawJson, "$.order.date");

assertThat(orderDate, is(1531380888L));
查看更多
登录 后发表回答