簡體   English   中英

使用JACKSON解析器解析特定的JSON數組

[英]Parse specific JSON array using JACKSON parser

 {
    "response": [
        {
            "id": "1",
            "name": "xx"
        },
        {
            "id": "2",
            "name": "yy"
        }
    ],
    "errorMsg": "",
    "code": 0
}

如何使用傑克遜解析器單獨解析“響應”。 我收到錯誤消息

Unrecognized field "errorMsg", not marked as ignorable.

我的模型類Response.java

public class Response {
@JsonProperty("id")
private Integer id;
@JsonProperty("name")
private String name;
}

您的數據模型有點不完整,這就是Jackson所指出的。 為了改善這種情況,您應該映射更多字段。

public class Response {
    @JsonProperty("id")
    private Integer id;
    @JsonProperty("name")
    private String name;
    // getter/setter...
}
public class Data {
    @JsonProperty("response")
    private List<Response> response;
    @JsonProperty("errorMsg")
    private String errorMsg;
    @JsonProperty("code")
    private int code;
    // getter/setter...
}

您可以創建一個父對象並使用@JsonIgnoreProperties 另外,您可以使用ObjectMapper's convertValue()方法獲取節點並將其轉換為響應對象,例如

try {
    String json = "{\"response\":[{\"id\":\"1\",\"name\":\"xx\"},{\"id\":\"2\",\"name\":\"yy\"}],\"errorMsg\":\"\",\"code\":0}";
    ObjectMapper mapper = new ObjectMapper();
    JsonNode node = mapper.readTree(json);
    List<Response> responses = mapper.convertValue(node.findValues("response").get(0), new TypeReference<List<Response>>() {});
    System.out.println(responses);
} catch (JsonProcessingException e) {
    e.printStackTrace();
} catch (IOException e) {
    e.printStackTrace();
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM