2

我正在使用杰克逊,我有以下 JSON 结构。

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

我想得到以下结果或将它们分开。
json1:

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

json2

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

怎么做?

4

3 回答 3

1

试试这个:

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);
于 2020-04-29T03:02:04.513 回答
1

当您尝试使用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));
    }
于 2020-04-29T06:39:19.627 回答
1

您可以读取整个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"}}
于 2020-04-29T10:03:51.197 回答