Parse specific JSON array using JACKSON parser
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | { "response": [ { "id":"1", "name":"xx" }, { "id":"2", "name":"yy" } ], "errorMsg":"", "code": 0 } |
如何使用jackson解析器单独解析"响应"。 我收到错误了
1 | Unrecognized field"errorMsg", not marked as ignorable. |
我的模型类Response.java
1 2 3 4 5 6 |
你的数据模型有点不完整,这正是杰克逊指出的。
要改善这种情况,您应该映射更多字段。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 | 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... } |
您可以创建父对象并使用
1 2 3 4 5 6 7 8 9 10 11 | 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(); } |