JsonPath - read Java Long type

Wojtek picture Wojtek · May 5, 2013 · Viewed 7.7k times · Source

I've got JSON data that looks like this

{"sessionID":7242750700467747000}

The number is previously obtained from server response and is generated server-side as Java Long. Client identifies itself thought this sessionID and sends it with requests. The problem is when the client's request arrives at the server I have to parse this value again to type Long. I use JsonPath, specifically:

<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

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

I get an exception:

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

So it looks like the number is parse by JsonPath as Integer. That will surely lead to wrong results, as Integer is smaller than Long. Is there any way in JsonPath to parse and return the data as Long?

Answer

radistao picture radistao · Aug 22, 2018

It's possible (json-path:2.4.0):

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

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