使用Jackson JSON映射其余响应

问题描述:

我有一个REST调用,可以返回AccountPojoErrorCodePojo.这些每个都有特定的字段.如何使用Jackson JSON库轻松解析响应并获取AccountPojoErrorCodePojo?

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:

  1. 将JSON反序列化为Map类.
  2. 检查地图是否包含类AccountPojo/ErrorCodePojo中的属性.
  3. 将地图转换为目标类.
  1. Deserialize JSON to Map class.
  2. Check if map contains property from class AccountPojo/ErrorCodePojo.
  3. 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);
}