単一の RESTful Web サービスから 2 つの異なるシナリオで 2 つの異なる種類の応答 json を取得します。Jackson で次の応答 json を解析する方法は??
response:{
result:"0"
}
と
response:{
result :{
fname: "abc",
lname: "xyz"
}
}
単一の RESTful Web サービスから 2 つの異なるシナリオで 2 つの異なる種類の応答 json を取得します。Jackson で次の応答 json を解析する方法は??
response:{
result:"0"
}
と
response:{
result :{
fname: "abc",
lname: "xyz"
}
}
JsonNode
最低限として として逆シリアル化し、いくつかのロジックを実行して正しい型を決定できます。特定の解決策を探している場合は、質問に詳細を追加してください。ここにあなたが始めるための何かがあります:
@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) {...}
}