Airwavezx
Airwavezx

Reputation: 957

Jayway JsonPath read long Java

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.

Upvotes: 2

Views: 1438

Answers (1)

glytching
glytching

Reputation: 47935

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

Upvotes: 2

Related Questions