【问题标题】:deserialize inner JSON object反序列化内部 JSON 对象
【发布时间】:2013-10-06 11:22:42
【问题描述】:

我有一个类 POJO

Class Pojo {
String id;
String name;
//getter and setter
}

我有一个类似的json

{
    "response" : [
        {
            "id" : "1a",
            "name" : "foo"
        }, 
        {
            "id" : "1b",
            "name" : "bar"
        }
    ]
}

我正在使用 Jackson ObjectMapper 进行反序列化。如何在不创建任何其他父类的情况下获得List<Pojo>

如果不可能,是否可以获得 Pojo 对象,该对象仅包含 json 字符串的第一个元素,即在本例中为 id="1a"name="foo"

【问题讨论】:

标签: java json jackson


【解决方案1】:
Pojo pojo;
json = {
    "response" : [
        {
            "id" : "1a",
            "name" : "foo"
        }, 
        {
            "id" : "1b",
            "name" : "bar"
        }
    ]
}
ObjectMapper mapper = new ObjectMapper();
JsonNode root = objectMapper.readTree(json);
pojo = objectMapper.readValue(root.path("response").toString(),new TypeReference<List<Pojo>>() {});

首先,您必须使用您的 JSON 文件创建一个 JSON 节点。现在您有了一个 JSON 节点。您可以像我一样使用 JSON 节点的路径功能转到所需的位置

root.path("response")

但是,这将返回一个 JSON 树。为了制作一个字符串,我使用了 toString 方法。 现在,您有一个如下所示的字符串 " [ { “id”:“1a”, “名称”:“富” }, { “id”:“1b”, “名称”:“酒吧” } ] " 您可以将此字符串与 JSON 数组映射如下

String desiredString = root.path("response").toString();
pojos = objectMapper.readValue(desiredString ,new TypeReference<List<Pojo>>() {});

【讨论】:

  • 您还应该解释您的答案,而不仅仅是发布代码。
  • 谢谢大家的建议。我会更新我的答案
【解决方案2】:

您可以将通用的 readTree 与 JsonNode 一起使用:

ObjectMapper mapper = new ObjectMapper();
JsonNode root = mapper.readTree(json);
JsonNode response = root.get("response");
List<Pojo> list = mapper.readValue(response, new TypeReference<List<Pojo>>() {});

【讨论】:

    【解决方案3】:

    你首先需要得到数组

    String jsonStr = "{\"response\" : [ { \"id\" : \"1a\",  \"name\" : \"foo\"},{ \"id\" : \"1b\",\"name\" : \"bar\"  } ]}";
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree(jsonStr);
    ArrayNode arrayNode = (ArrayNode) node.get("response");
    System.out.println(arrayNode);
    List<Pojo> pojos = mapper.readValue(arrayNode.toString(), new TypeReference<List<Pojo>>() {});
    
    System.out.println(pojos);
    

    打印(带有toString()

    [{"id":"1a","name":"foo"},{"id":"1b","name":"bar"}] // the json array 
    [id = 1a, name = foo, id = 1b, name = bar] // the list contents
    

    【讨论】:

      猜你喜欢
      • 2021-12-08
      • 2021-01-19
      • 2015-02-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多