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?
JsonPath is to JSON what XPATH is to XML, a simple way to extract parts of a given document. JsonPath is available in many programming languages such as Javascript, Python and PHP. JsonPath allows you to compile a json path string to use it many times or to compile and apply in one single on demand operation.
JSONPath creates a uniform standard and syntax to define different parts of a JSON document. JSONPath defines expressions to traverse through a JSON document to reach to a subset of the JSON. This topic is best understood by seeing it in action. We have created a web page which can help you evaluate a JSONPath.
You use a JSONPath expression to traverse the path to an element in the JSON structure. You start at the root node or element, represented by $, and reach the required element in the JSON structure to extract data from it. You can use either the dot-notation or the bracket-notation to form the expressions.
The Jayway JsonPath library has support for reading values using a JSON path. If you would like to specifically use GSON or Jackson to do the deserialization (the default is to use json-smart), you can also configure this: Configuration.
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
Ok, I managed to do it changing the JsonPath provider a bit. 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With