如何将 JSON 个对象分开?

How to separate JSON object on pieces?

我正在使用 Jackson,我有以下 JSON 结构。

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

我想得到下面的结果,或者把它们分开。
Json1:

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

Json2

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

怎么做?

试试这个:

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);

当您尝试 jackson 时...这里是 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));
    }

您可以将整个 JSON 有效载荷读取为 JsonNode 并遍历所有字段并创建新的 JSON Object-s。请参阅以下示例:

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);
        });
    }
}

以上代码打印:

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