嵌套多个级别的Jackson WRAPPER_OBJECT

时间:2014-11-20 10:58:25

标签: java json jackson wrapper

我绝不是Jackon / JSON向导,这可能是我遇到的以下问题所显而易见的:

我有两种可能的数据结构。 第一个叫做amountTransaction:

{
  "amountTransaction": {
    "clientCorrelator":"54321",
    "endUserId":"tel:+16309700001"
  }
}

由以下Java对象表示:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonTypeName(value = "amountTransaction")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AmountTransaction {
  private String clientCorrelator;
  private String endUserId;
  ...
}

但是,amountTransaction对象也显示为paymentTransactionNotification对象的子元素:

{
  "paymentTransactionNotification": {
    "amountTransaction": {
      "clientCorrelator": "54321",
      "endUserId": "tel:+16309700001"
    }
  }
}

..我认为将代表:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonTypeInfo(use = JsonTypeInfo.Id.NAME, include = JsonTypeInfo.As.WRAPPER_OBJECT)
@JsonTypeName(value = "paymentTransactionNotification")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentTransactionNotification {
  private AmountTransaction amountTransaction;
  ...
}

仅使用amountTransaction对象解析JSON就可以了。这是一个非常简单的WRAPPER_OBJECT示例。

但是,在尝试解析PaymentTransactionNotification的JSON时,我收到一个异常,表明它无法正确处理amountTransaction作为paymentTransactionNotification的元素:

com.fasterxml.jackson.databind.JsonMappingException: Could not resolve type id 'clientCorrelator' into a subtype of [simple type, class com.sf.oneapi.pojos.AmountTransaction]

有关如何正确注释这一点的任何想法,以便我的代码可以正确处理独立的,以及封装的amountTransaction对象?

1 个答案:

答案 0 :(得分:5)

默认情况下,禁用Jackson中的根节点。您可以包装内部对象,但如果要包装根节点,则需要为其启用jackson功能(https://jira.codehaus.org/browse/JACKSON-747):

ObjectMapper objectMapper = new ObjectMapper();
objectMapper.enable(SerializationConfig.Feature.WRAP_ROOT_VALUE);
objectMapper.enable(DeserializationConfig.Feature.UNWRAP_ROOT_VALUE);

当你启用这些功能时,你已经说杰克逊要包装根元素,你不再需要@JsonTypeInfo和@JsonTypeName。你可以简单地删除它们。但是现在您需要自定义根节点名称,并且可以使用@JsonRootName。您的课程应如下所示:

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonRootName("amountTransaction")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AmountTransaction {
    private String clientCorrelator;
    private String endUserId;
...............
}

@JsonIgnoreProperties(ignoreUnknown = true)
@JsonRootName("paymentTransactionNotification")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentTransactionNotification {
  private AmountTransaction amountTransaction;
.............
}

我已经尝试过,Jackson按预期转换了两个JSON请求。