我从单个 RESTful Web 服务的两个不同场景中得到两种不同类型的响应 json,如何使用 Jackson 解析以下响应 json?
response:{
result:"0"
}
和
response:{
result :{
fname: "abc",
lname: "xyz"
}
}
我从单个 RESTful Web 服务的两个不同场景中得到两种不同类型的响应 json,如何使用 Jackson 解析以下响应 json?
response:{
result:"0"
}
和
response:{
result :{
fname: "abc",
lname: "xyz"
}
}
JsonNode
您可以至少反序列化为 a并执行一些逻辑来确定正确的类型。如果您正在寻找特定的解决方案,请在您的问题中添加更多详细信息。这里有一些让你开始的东西:
@Test
public void testDoubleResponseType() throws IOException {
ImmutableList<String> jsonInputs = ImmutableList.of(
"{\"result\": \"0\"}",
"{\"result\": {\"fname\": \"abc\", \"lname\": \"xyz\"}}"
);
ObjectMapper om = new ObjectMapper();
for (String jsonInput : jsonInputs) {
JsonNode node = om.readValue(jsonInput, JsonNode.class);
JsonNode result = node.get("result");
if (result.isTextual()) {
assertEquals("0", result.asText());
} else if (result.isObject()) {
NameResponse nameResponse =
om.readValue(result.toString(), NameResponse.class);
assertEquals(new NameResponse("abc", "xyz"), nameResponse);
} else {
fail();
}
}
}
public static class NameResponse {
private final String fname;
private final String lname;
@JsonCreator
public NameResponse(@JsonProperty("fname") String fname,
@JsonProperty("lname") String lname) {
this.fname = fname;
this.lname = lname;
}
public String getFname() {
return fname;
}
public String getLname() {
return lname;
}
@Override
public boolean equals(Object o) {...}
}