2

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?

Michał Ziober
  • 37,175
  • 18
  • 99
  • 146
Daniel
  • 181
  • 4
  • 13

3 Answers3

1

Try this one :

String jsonstring = "{\r\n" + 
            "      \"person\":{\r\n" + 
            "        \"person1\": {\"name\": \"daniel\", \"age\":\"17\"},\r\n" + 
            "        \"person2\": {\"name\": \"lucy\", \"age\": 19}\r\n" + 
            "      }\r\n" + 
            "    }";
    JSONParser parser = new JSONParser();
    Object obj = parser.parse(jsonstring);
    JSONObject jsonObject = (JSONObject) obj;
    JSONObject persons = (JSONObject) jsonObject.get("person");
    JSONObject person1= (JSONObject) persons.get("person1");
    System.out.println(person1);
    JSONObject person2= (JSONObject) persons.get("person2");
    System.out.println(person2);
maryem neyli
  • 467
  • 3
  • 20
1

As you try with jackson... here is an example with JsonNode..

public static void main(String[] args) throws Exception {
        String json = "{\n" +
                "      \"person\":{\n" +
                "        \"person1\": {\"name\": \"daniel\", \"age\":\"17\"},\n" +
                "        \"person2\": {\"name\": \"lucy\", \"age\": \"19\"}\n" +
                "      }\n" +
                "    }";
        ObjectMapper objectMapper = new ObjectMapper();
        JsonNode jsonNode = objectMapper.readTree(json);
        JsonNode json1 = jsonNode.get("person").get("person1");
        JsonNode json2 = jsonNode.get("person").get("person2");
        System.out.println("Json 1: "+objectMapper.writeValueAsString(json1));
        System.out.println("Json 2: "+objectMapper.writeValueAsString(json2));
    }
GolamMazid Sajib
  • 8,698
  • 6
  • 21
  • 39
1

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"}}
Michał Ziober
  • 37,175
  • 18
  • 99
  • 146