Update values in Post Data using Json Path in Rest Assured




In the previous post we studied about how to validate json schema in Rest Assured. In this post we will study about how to update values in Post Data (JSON) using Json Path in Rest Assured.


When we have multiple dynamic values in POST Data which will change every time  then we need to read those values from previous request and use those values to update the POST Data (JSON). This is specifically used when the hardcoded values in JSON Data like specific ID's won't work.For example in following POST Data :


{"id":1,"name":"ashwin","surname":"karangutkar","details":{"City":"Mumbai"}}

If I need to change City then Json Path that we will use is details.City.

Before having a glance at code, we will need to import Jayways JsonPathFollowing is the maven import:

<!-- https://mvnrepository.com/artifact/com.jayway.jsonpath/json-path -->
<dependency>
    <groupId>com.jayway.jsonpath</groupId>
    <artifactId>json-path</artifactId>
    <version>2.4.0</version>
</dependency>

Now let us have a look at Code Snippet:

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

public class ConvertStringToJson {

 public static void main(String[] args) {

   String jsonString = "{\"id\":1,\"name\":\"ashwin\",\"surname\":\"karangutkar\",\"details\":{\"City\":\"Mumbai\"}}\\";

   Configuration configuration = Configuration.builder().jsonProvider(new JacksonJsonNodeJsonProvider())
   .mappingProvider(new JacksonMappingProvider()).build();

          DocumentContext json = JsonPath.using(configuration).parse(jsonString);
   String jsonPath = "details.City";
   String newValue = "Pune";
   System.out.println(json.set(jsonPath, newValue).jsonString());

 }
}


In the above code, jsonString is the string that we need to update. We configure the jsonProvider using Configuration builder. Now we pass the configuration object to using method of JsonPath and pass the json string to parse method which will return the parsed JSON.Then we pass the json path of the value that needs to be updated and the new value that we need in post Data to set method, which returns the updated POST (JSON) Data.

Output:

Comments

Popular posts from this blog

Extracting an XML Response with Rest-Assured