Search code examples
javarest-assured-jsonpath

In Rest Assured, getString() round off the decimal values after 4 digit


I have scenario, we need to read the latitude and Longitude from json response body. The latitude and longitude has value like below

"data": [{
  "city": "Mumbai",
  "country": "India",  
  "latitude": 19.0886993408,
  "longitude": 72.8678970337
  
}

when We try to validate the JSON response by reading the latitude and longitude using JSONPATH using getString() then it round off the value after 4 digit in decimal places.

Below is the code in java

String key = item.getKey();
String value = item.getValue();
JsonPath jsonPathEvaluator = response.jsonPath();
String strjson = jsonPathEvaluator.getString(key).toString().replaceAll("\\[\\](){}]", "");

Output display:

Latitude:-19.0887 instead of 19.0886993408


Solution

  • You can try with JsonPath.config as mentioned here

    Using it you can provide your custom configuration for JsonPath. Here i am just trying to convert my numeric data with long decimal range double.

    String key = item.getKey();
    String value = item.getValue();
    JsonPath jsonPathEvaluator = response.jsonPath();
    JsonPath.config = new JsonPathConfig(JsonPathConfig.NumberReturnType.DOUBLE);
    String strjson = jsonPathEvaluator.getString(key).toString().replaceAll("\\[\\](){}]", "");
    
    
    /* String json = "{\n" +
    "  \"data\": {\n" +
    "    \"city\": \"Mumbai\",\n" +
    "    \"country\": \"India\",\n" +
    "    \"latitude\": 19.0886993408,\n" +
    "    \"longitude\": 72.8678970337\n" +
    "  }\n" +
    "}";
    JsonPath jsonPath = JsonPath.from(json);
    JsonPath.config = new JsonPathConfig(JsonPathConfig.NumberReturnType.DOUBLE);
    double strjson = jsonPath.get("data.latitude");
        
    System.out.println(String.valueOf(strjson)); */
    

    For me it's printing below output.

    19.0886993408