[英]Parse response using Jackson
I am trying to parse the api response using Jackson. 我正在尝试使用Jackson解析api响应。 getting errors like com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Health"
出现类似com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException之类的错误:无法识别的字段“健康”
I have tried options like 我尝试了类似的选项
objectMapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); //with true
I think simple mistake but not able to figure out. 我认为是简单的错误,但无法弄清楚。 please help
请帮忙
Response json: 响应json:
{
"Health": {
"id": "abc_Server",
"name": "ABC Request Service",
"status": "GREEN",
"dependencies": [
{
"id": "DB",
"name": "MySQL",
"message": "Connection successful.",
"status": "GREEN"
}
]
}
}
java pojos 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
}
main class: 主类:
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){
//
}
Also tried have a pojo with but did not work 也尝试过与一个pojo,但没有用
@JsonRootName(value = "Health")
public class Health {
private HealthResponse health;
//getter and setter
}
When converting JSON to Java object you're actually deserializing, not serializing. 将JSON转换为Java对象时,您实际上是在反序列化而不是序列化。 So use this:
所以使用这个:
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
Complete code that's currently working for me (prints abc_Server): 目前对我有用的完整代码(打印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();
}
And HealthResponse
: 和
HealthResponse
:
@JsonRootName(value = "Health")
class HealthResponse {
[...]
}
No change in Dependencies
Dependencies
不变
Documentation for UNWRAP_ROOT_VALUE . UNWRAP_ROOT_VALUE的文档。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.