使用Jackson JSON映射其余响应
问题描述:
我有一个REST
调用,可以返回AccountPojo
或ErrorCodePojo
.这些每个都有特定的字段.如何使用Jackson JSON
库轻松解析响应并获取AccountPojo
或ErrorCodePojo
?
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
?
我有类似的东西:
ObjectMapper mapper = new ObjectMapper();
try {
ret = mapper.readValue(json, AccountPojo.class);
} catch (JsonProcessingException e) {
ret = mapper.readValue(json, ErrorCodePojo.class);
}
但我认为这不好.
谢谢!
答
You can also use ObjectMapper#convertValue
method. With this method your parsing algorithm could look like this:
- 将JSON反序列化为
Map
类. - 检查地图是否包含类
AccountPojo
/ErrorCodePojo
中的属性. - 将地图转换为目标类.
- Deserialize JSON to
Map
class. - Check if map contains property from class
AccountPojo
/ErrorCodePojo
. - Convert map to the target class.
例如,假设您的ErrorCodePojo
类如下所示:
For example, let's assume that your ErrorCodePojo
class looks like this:
class ErrorCodePojo {
private int errroCode;
private String message;
//getters, setters
}
属性errroCode
仅存在于ErrorCodePojo
中. AccountPojo
不包含此属性.
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);
}