简体   繁体   English

JsonPath - 读取Java Long类型

[英]JsonPath - read Java Long type

I've got JSON data that looks like this 我有JSON数据,看起来像这样

{"sessionID":7242750700467747000} { “会话ID”:7242750700467747000}

The number is previously obtained from server response and is generated server-side as Java Long. 该号码先前从服务器响应中获取,并在服务器端生成为Java Long。 Client identifies itself thought this sessionID and sends it with requests. 客户端认为自己认为这个sessionID并发送请求。 The problem is when the client's request arrives at the server I have to parse this value again to type Long. 问题是当客户端的请求到达服务器时,我必须再次解析此值以键入Long。 I use JsonPath, specifically: 我使用JsonPath,具体来说:

<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path-assert</artifactId>
    <version>0.8.1</version>
    <scope>test</scope>
</dependency>

When I parse the JSON data like this 当我像这样解析JSON数据时

Long sessionID = JsonPath.read(json, "$.sessionID"); long sessionID = JsonPath.read(json,“$ .sessionID”);

I get an exception: 我得到一个例外:

java.lang.ClassCastException: java.lang.Integer cannot be cast to java.lang.Long java.lang.ClassCastException:java.lang.Integer无法强制转换为java.lang.Long

So it looks like the number is parse by JsonPath as Integer. 因此看起来这个数字是由JsonPath解析为Integer的。 That will surely lead to wrong results, as Integer is smaller than Long. 这肯定会导致错误的结果,因为Integer小于Long。 Is there any way in JsonPath to parse and return the data as Long? 在JsonPath中有什么办法可以解析并将数据作为Long返回吗?

Ok, I managed to do it changing the JsonPath provider a bit. 好的,我设法做了一点改变JsonPath提供程序。 Now I use: 现在我使用:

<dependency>
    <groupId>com.jayway.restassured</groupId>
    <artifactId>rest-assured</artifactId>
    <version>1.7.2</version>
</dependency>

From there I can use 从那里我可以使用

import com.jayway.restassured.path.json.JsonPath;
// ...
Long sessionID = JsonPath.with(json).getLong("sessionID");

Notation in this library is the same except for the lack of $. 除了缺少$.之外,这个库中的符号是相同的$. at the beginning, wich I don't find necessary at all. 一开始,我根本没有必要。

It's possible ( json-path:2.4.0 ): 这是可能的( json-path:2.4.0 ):

JsonPath.parse(json).read("$.sessionID", Long.class);

See more: https://github.com/json-path/JsonPath#what-is-returned-when 查看更多: https//github.com/json-path/JsonPath#what-is-returned-when

For what I've seen, the API does not provide this option. 对于我所看到的,API不提供此选项。

So I see two options for you: 所以我看到了两个选项:

  1. On JSON serialization, make sessionId a String. 在JSON序列化上,使sessionId成为String。 Read a String and then parse to Long. 读取一个String,然后解析为Long。
  2. Use Jackson , to make the JSON read. 使用Jackson ,使JSON读取。 This will allow you to read a Long. 这将允许您阅读Long。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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