javajsonjacksonunwrapjsonnode

How to separate JSON object on pieces?


I am using Jackson and I have the following JSON structure.

{
  "person": {
    "person1": {"name": "daniel", "age": "17"},
    "person2": {"name": "lucy", "age": "19"}
  }
}

And I want to get the following result or separate them.
Json1:

{
  "person1": {"name": "daniel", "age": "17"},
}

Json2

{
  "person2": {"name": "lucy", "age": "19"}
}

How to do that?


Solution

  • You can read the whole JSON payload as JsonNode and iterate over all fields and create new JSON Object-s. See below example:

    import com.fasterxml.jackson.databind.JsonNode;
    import com.fasterxml.jackson.databind.ObjectMapper;
    
    import java.io.File;
    import java.io.IOException;
    
    public class JsonNodeApp {
    
        public static void main(String[] args) throws IOException {
            File jsonFile = new File("./resource/test.json").getAbsoluteFile();
    
            ObjectMapper mapper = new ObjectMapper();
    
            JsonNode person = mapper.readTree(jsonFile).get("person");
            person.fields().forEachRemaining(entry -> {
                JsonNode newNode = mapper.createObjectNode().set(entry.getKey(), entry.getValue());
                System.out.println(newNode);
            });
        }
    }
    

    Above code prints:

    {"person1":{"name":"daniel","age":"17"}}
    {"person2":{"name":"lucy","age":"19"}}