简体   繁体   中英

Parse specific JSON array using JACKSON parser

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

How to parse "response" alone using jackson parser. I am getting error as

Unrecognized field "errorMsg", not marked as ignorable.

My model class Response.java

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

Your data model is a bit incomplete and this is what Jackson is pointing out. To improve the situation you should map more fields.

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...
}

You can either create a parent object and use @JsonIgnoreProperties . Alternatievly you could get the node and convert it to response object using ObjectMapper's convertValue() method like

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM