Java 嵌套多个级别的JACKSOU对象
我决不是一个Jackon/JSON向导,这可能从我遇到的以下问题中可以看出: 我收到了两种可能的数据结构。 第一个称为amountTransaction:Java 嵌套多个级别的JACKSOU对象,java,json,jackson,wrapper,Java,Json,Jackson,Wrapper,我决不是一个Jackon/JSON向导,这可能从我遇到的以下问题中可以看出: 我收到了两种可能的数据结构。 第一个称为amountTransaction: { "amountTransaction": { "clientCorrelator":"54321", "endUserId":"tel:+16309700001" } } 由以下Java对象表示: @JsonIgnoreProperties(ignoreUnknown = true) @JsonTypeInfo(
{
"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就可以了。这是一个非常简单的包装器对象示例
但是,在尝试解析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对象?默认情况下,在Jackson中包装根节点是禁用的。可以包装内部对象,但如果要包装根节点,则需要为其启用jackson功能(): 当您启用这些功能时,您已经说过Jackson要包装根元素,您不再需要@JsonTypeInfo和@JsonTypeName。您可以简单地删除它们。但是现在需要自定义根节点名称,并且可以使用@JsonRootName。您的类应该如下所示:
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonRootName("amountTransaction")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AmountTransaction {
private String clientCorrelator;
private String endUserId;
...............
}
及
我已经尝试过了,Jackson按照预期转换了两个JSON请求。我认为您应该展示您认为这应该如何映射到POJO——我不太清楚它将如何工作,因为POJO的属性有名称,您的JSON似乎缺少这部分信息。我本打算很快与您交谈,并说它还不起作用,但后来我意识到我忘了在我的单元测试objectMapper上设置功能。是的,这很好用。唯一需要注意的是,在Jackson 2.4.0中,功能常量发生了一些变化:
objectMapper.enable(SerializationFeature.WRAP_ROOT_值);enable(反序列化功能。展开根值)
我也有类似的与嵌套字段相关的内容,我对如何创建嵌套级别的POJO以及如何从最后一级的parentCategory
提取id感到困惑?我想看看你能不能帮我。
@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;
.............
}