【发布时间】:2017-02-01 14:56:07
【问题描述】:
我使用的是 java 8 和 (fasterjackson) Jackson 2.8.1。
我有一个需要使用 Java 将其转换为 json 的 xml。 xml结构是这样的:
<Input>
<ns0:order>
<ns0:lineItemList>
<ns0:lineItem>
<ns0:lineItemType>
<ns0:orderID>234</ns0:orderID>
<ns0:shipmentID>1</ns0:shipmentID>
<ns0:lineID>1</ns0:lineID>
<ns0:upc>123</ns0:upc>
<ns0:quantity>1</ns0:quantity>
<ns0:retailPrice>14</ns0:retailPrice>
</ns0:lineItemType>
</ns0:lineItem>
</ns0:lineItemList>
</ns0:order>
</Input>
我选择Jackson从xml反序列化成java,然后再从java序列化成json。目标json需要解包“lineItem”和“lineItemType”才能得到类似这样的json:
{
"input" : {
"order" : {
"lineItemList" : [ {
"upc" : 123,
"quantity" : 1,
"retailPrice" : 14,
"orderID" : 234,
"shipmentID" : 1,
"lineID" : 1
} ]
}
}
}
在我的 java 模型中,这里有 3 个相关的类:Order、LineItem 和 LineItemType。在订单类中,我这样注释:
@JacksonXmlProperty(localName="lineItemList")
@JsonProperty("lineItemList")
List<LineItem> lineItems;
在 LineItem 中,像这样:
@JacksonXmlProperty(localName="lineItemType")
@JsonUnwrapped
LineItemType lineItemType;
在 LineItemType 中它只是具有这种模式的属性:
...
@JacksonXmlProperty(localName="orderID")
@JsonProperty("orderID")
String orderId;
@JacksonXmlProperty(localName="lineID")
@JsonProperty("lineID")
String lineId;
...
如您所见,我尝试通过在 LineItem 类中使用 @JsonUnwrapped 来解决此问题,但最终结果是 XMLDeserializer 最终读取此注释并生成“null”值:
{
"input" : {
"order" : {
"lineItemList" : [ {
"upc" : null,
"quantity" : null,
"retailPrice" : null,
"orderID" : null,
"shipmentID" : null,
"lineID" : null
} ]
}
}
}
如果我省略了@JsonUnwrapped,值就会进来,但是像这样嵌套:
{
"input" : {
"order" : {
"lineItemList" : [ {
"lineItemType" : {
"upc" : 123,
"quantity" : 1,
"retailPrice" : 14,
"orderID" : 234,
"shipmentID" : 1,
"lineID" : 1
} ]
}
}
}
}
有谁知道应该如何注释才能在此处获得所需的结果(未包装但带有值)?谢谢!
【问题讨论】: