I am trying to parse the api response using Jackson. getting errors like com.fasterxml.jackson.databind.exc.UnrecognizedPropertyException: Unrecognized field "Health"
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:
{
"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
}
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
@JsonRootName(value = "Health")
public class Health {
private HealthResponse health;
//getter and setter
}
When converting JSON to Java object you're actually deserializing, not serializing. So use this:
objectMapper.configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true);
Complete code that's currently working for me (prints 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
:
@JsonRootName(value = "Health")
class HealthResponse {
[...]
}
No change in Dependencies
Documentation for UNWRAP_ROOT_VALUE.