[英]Parse response using Jackson
我正在尝试使用Jackson解析api响应。 出现类似com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException之类的错误:无法识别的字段“健康”
我尝试了类似的选项
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); //with true
我认为是简单的错误,但无法弄清楚。 请帮忙
响应json:
{
"Health": {
"id": "abc_Server",
"name": "ABC Request Service",
"status": "GREEN",
"dependencies": [
{
"id": "DB",
"name": "MySQL",
"message": "Connection successful.",
"status": "GREEN"
}
]
}
}
java pojos
@JsonRootName(value = "Health")
public class HealthResponse {
private String id;
private String name;
private String status;
private List<Dependencies> dependencies;
//getter and setter methods
}
}
public class Dependencies {
private String id;
private String name;
private String message;
private String status;
//getter and setter methods
}
主类:
ObjectMapper objectMapper = new ObjectMapper();
try {
InputStream response = healthCheckWebTarget.request(MediaType.APPLICATION_JSON).get(InputStream.class);
HealthResponse healthResponse = objectMapper.readValue(response, HealthResponse.class);
}catch(Exception e){
//
}
也尝试过与一个pojo,但没有用
@JsonRootName(value = "Health")
public class Health {
private HealthResponse health;
//getter and setter
}
将JSON转换为Java对象时,您实际上是在反序列化而不是序列化。 所以使用这个:
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
目前对我有用的完整代码(打印abc_Server):
String json="{\"Health\":{\"id\":\"abc_Server\",\"name\":\"ABCRequestService\",\"status\":\"GREEN\",\"dependencies\":[{\"id\":\"DB\",\"name\":\"MySQL\",\"message\":\"Connectionsuccessful.\",\"status\":\"GREEN\"}]}}";
ObjectMapper objectMapper = new ObjectMapper();
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
try {
HealthResponse healthResponse = objectMapper.readValue(json, HealthResponse.class);
System.out.println(healthResponse.getId());
} catch (Exception e) {
e.printStackTrace();
}
和HealthResponse
:
@JsonRootName(value = "Health")
class HealthResponse {
[...]
}
Dependencies
不变
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.