Jayway JsonPath读了很长的Java [英] Jayway JsonPath read long Java

查看:226
本文介绍了Jayway JsonPath读了很长的Java的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在JSON中,我收到了一个unix时间戳:

In JSON i receive a unix timestamp:

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

我想将此值读入long,以便可以从中创建Date对象:

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

但是JSONPath坚持不能将此整数转换为long:

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

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

是否可以通过Jsonpath读取Long或自动将unix时间戳转换为Java日期对象?

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

进口:

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

整数问题:最大值为2147483647,即为Tuesday, January 19, 2038 3:14:07 AM GMT.不能将Integer用于Unix时间戳. 谢谢.

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.

推荐答案

您可以配置JsonPath使用的ObjectMapper将整数视为long.这样可以确保所有整数值(和long值)都以long形式返回.

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.

这是一个例子:

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

这篇关于Jayway JsonPath读了很长的Java的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆