使用Jackson JSON映射其余响应 [英] mapping rest responses with Jackson JSON

查看:49
本文介绍了使用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);
}

这篇关于使用Jackson JSON映射其余响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆