mapping rest responses with Jackson JSON

亡梦爱人 提交于 2021-01-28 07:00:38

问题


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:

  1. Deserialize JSON to Map class.
  2. Check if map contains property from class AccountPojo/ErrorCodePojo.
  3. 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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!