问题
I have a REST
call that can return either AccountPojo
or ErrorCodePojo
. Each of these have specific fields. How can I use the Jackson JSON
libary to easily parse the response and fetch AccountPojo
or the ErrorCodePojo
?
I have something like:
ObjectMapper mapper = new ObjectMapper();
try {
ret = mapper.readValue(json, AccountPojo.class);
} catch (JsonProcessingException e) {
ret = mapper.readValue(json, ErrorCodePojo.class);
}
but I don't think this is nice.
Thanks!
回答1:
You can also use ObjectMapper#convertValue method. With this method your parsing algorithm could look like this:
- Deserialize JSON to
Map
class. - Check if map contains property from class
AccountPojo
/ErrorCodePojo
. - Convert map to the target class.
For example, let's assume that your ErrorCodePojo
class looks like this:
class ErrorCodePojo {
private int errroCode;
private String message;
//getters, setters
}
Property errroCode
exists only in ErrorCodePojo
. AccountPojo
does not contain this property.
// Step 1
Map<?, ?> value = mapper.readValue(json, Map.class);
// Step 2
if (value.containsKey("errroCode")) {
// Step 3
mapper.convertValue(value, ErrorCodePojo.class);
} else {
// Step 3
mapper.convertValue(value, AccountPojo.class);
}
来源:https://stackoverflow.com/questions/21004643/mapping-rest-responses-with-jackson-json