skip to Main Content

I have a nested JSON structure. I want to retrieve only a particular branch of the structure and ignore rest of the objects in the json. I am not sure on the approach to achieve this. Please suggest.
For example:

{
"prop1":"val1",
"prop2":{
  "child":"childval"
},
"prop3":{
 "child":"childval"
}

}

Here, I want to retrieve only prop3 along with prop1 ignoring prop2.

{
"prop1":"val1",
"prop3":{
 "child":"childval"
}
}

Would it require the usage of jackson libraries?

2

Answers


  1. If you’re using Jackson, it will deserialize only the stuff you define.
    Here is some code (that uses lombok for the getters and setters).
    First define classes that represent the JSON structure.

    @Getter
    @Setter
    public class Prop3
    {
      private String child;
    }
    
    @Getter
    @Setter
    public class Blammy
    {
      private String prop1;
      private Prop3 prop3;
    }
    

    Here is code to deserialize the JSON from a String.

    Blammy blammy;
    ObjectMapper mapper = new ObjectMapper();
    
    blammy = mapper.readValue(jsonString, Blammy.class);
    
    Login or Signup to reply.
  2. Any Java library for JSON (de)serialization should be able to handle this, but here is how you can achieve it using Jackson:

        // Required imports
    
        public static String removeProps(String json, List<String> propertiesToRemove) throws Exception {
            ObjectMapper mapper = new ObjectMapper();
            JsonNode rootNode = mapper.readTree(json);
    
            propertiesToRemove.forEach(prop -> removeProp(rootNode, prop));
    
            return rootNode.toString();
        }
    
        public static void removeProp(JsonNode node, String prop) {
            if (node.isObject()) {
                ObjectNode objectNode = (ObjectNode) node;
                if (objectNode.has(prop)) {
                    objectNode.remove(prop);
                } else {
                    objectNode.fields().forEachRemaining(entry -> removeProp(entry.getValue(), prop));
                }
            } else if (node.isArray()) {
                node.elements().forEachRemaining(element -> removeProp(element, prop));
            }
        }
    
    // Example usage
    String json = "{"prop1":"val1","prop2":{"child":"childval"},"prop3":{"child":"childval"}}";
    
    List<String> propsToRemove = List.of("prop2");
    String jsonWithoutProps = removeProps(json, propsToRemove);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search