carlos
carlos

Reputation: 63

Retrieve get a jsonNode form the input json in java8

I have he following jsonObject:

{
  "payloadTesting": {
    "A": "a",
    "B": 21,
    "node that I want to remove": {
        "C": "123",
        "D": "456"
    }
  }
}

What I want to to is to go to the location of the 'node that I want to remove' and remove it from the original payload,so my final json would be:

{
  "payloadTesting": {
    "A": "a",
    "B": 21
  }
}

To do that I searched for the JsonPath library and tryied to use it like this:

private String retrievePayload(String payloadToRetrieve, String path) {
    return JsonPath
            .using(Configuration.builder().jsonProvider(new JsonOrgJsonProvider())
                    .options(Option.REQUIRE_PROPERTIES).build())
            .parse(enrichedFieldName)
            .jsonString();
}

But that solution only returns me the name 'node that I want to retrieve' and not the payload without that node. And this does not verify if that same node is on the correct path or not, because I only what to remove that node if it is on the correct path.

For example, I only want to remove the node if it is on the root ("$"). If it was on the $.A, for example, I dont want to remove it.

How can I do this correctly?

Upvotes: 0

Views: 251

Answers (1)

aziz shaw
aziz shaw

Reputation: 144

I know it's late but maybe helpful for others, here I have used 2 ways to do it

import com.google.gson.Gson;
import com.google.gson.JsonObject;
import com.jayway.jsonpath.DocumentContext;
import com.jayway.jsonpath.JsonPath;

public class test1 {
    
    public static void main(String[] args) {
        Gson gson = new Gson();
        
        
        String request = "{\r\n" + 
                "  \"payloadTesting\": {\r\n" + 
                "    \"A\": \"a\",\r\n" + 
                "    \"B\": 21,\r\n" + 
                "    \"node that I want to remove\": {\r\n" + 
                "        \"C\": \"123\",\r\n" + 
                "        \"D\": \"456\"\r\n" + 
                "    }\r\n" + 
                "  }\r\n" + 
                "}";
        // method 1 using google Gson
        
          JsonObject json = gson.fromJson(request, JsonObject.class);
          json.getAsJsonObject("payloadTesting").remove("node that I want to remove");
          System.out.println("deleted using gson:"+json);
         
        
        // method 2 using library com.jayway.jsonpath.DocumentContext 
        
        DocumentContext doc = JsonPath.parse(request);
        String  jsonPath="$.payloadTesting[\"node that I want to remove\"]";
        doc.delete(jsonPath);
        String JsonAfterDelete = doc.jsonString();
        System.out.println("deleted using pathway:"+JsonAfterDelete);
    
    }

}

Upvotes: 1

Related Questions