unc*_*ase 10 java json wrapper jackson
我绝不是一个Jackon/JSON向导,这可能从我遇到的以下问题中可以看出:
我有两种可能的数据结构.第一个叫做amountTransaction:
{
"amountTransaction": {
"clientCorrelator":"54321",
"endUserId":"tel:+16309700001"
}
}
Run Code Online (Sandbox Code Playgroud)
其中由以下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;
...
}
Run Code Online (Sandbox Code Playgroud)
但是,amountTransaction对象也显示为paymentTransactionNotification对象的子元素:
{
"paymentTransactionNotification": {
"amountTransaction": {
"clientCorrelator": "54321",
"endUserId": "tel:+16309700001"
}
}
}
Run Code Online (Sandbox Code Playgroud)
..我认为会代表:
@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;
...
}
Run Code Online (Sandbox Code Playgroud)
仅使用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]
Run Code Online (Sandbox Code Playgroud)
有关如何正确注释这一点的任何想法,以便我的代码可以正确处理独立,以及封装的amountTransaction对象?
默认情况下,禁用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);
Run Code Online (Sandbox Code Playgroud)
当你启用这些功能时,你已经说杰克逊要包装根元素,你不再需要@JsonTypeInfo和@JsonTypeName.你可以简单地删除它们.但是现在您需要自定义根节点名称,并且可以使用@JsonRootName.您的课程应如下所示:
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonRootName("amountTransaction")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class AmountTransaction {
private String clientCorrelator;
private String endUserId;
...............
}
Run Code Online (Sandbox Code Playgroud)
和
@JsonIgnoreProperties(ignoreUnknown = true)
@JsonRootName("paymentTransactionNotification")
@JsonInclude(JsonInclude.Include.NON_NULL)
public class PaymentTransactionNotification {
private AmountTransaction amountTransaction;
.............
}
Run Code Online (Sandbox Code Playgroud)
我已经尝试过,杰克逊按预期转换了两个JSON请求.
| 归档时间: |
|
| 查看次数: |
6023 次 |
| 最近记录: |