我的输入 XML 字符串包含一个条目列表。当我使用 jackson xmlmapper 将其反序列化为对象时,我看到列表中只有一项即将到来。父元素已被定义为 POJO 中的通用对象。
xml 字符串(ItemList 包含 3 个项目):
<msg>
<head>
<Client>MyClient</Client>
<RoutingArea>Test</RoutingArea>
<ServerId>ABCXYZ123</ServerId>
</head>
<body>
<UserDetailResponse>
<UserDetail>
<Customer>
<CustomerId>1456342711975</CustomerId>
<BusinessUnit>TEST0000</BusinessUnit>
<Name>
<Salutation>U</Salutation>
<First>TROPICAL TAN</First>
</Name>
<Privacy>Y</Privacy>
</Customer>
<ItemList>
<Count>3</Count>
<Item>
<ServiceIdentifier>000001</ServiceIdentifier>
<BillingIdentifier>000001</BillingIdentifier>
</Item>
<Item>
<ServiceIdentifier>000002</ServiceIdentifier>
<BillingIdentifier>000002</BillingIdentifier>
</Item>
<Item>
<ServiceIdentifier>000003</ServiceIdentifier>
<BillingIdentifier>000003</BillingIdentifier>
</Item>
</ItemList>
</UserDetail>
</UserDetailResponse>
</body>
</msg>
Java代码:
private final static XmlMapper mapper = new XmlMapper();
public static <T> T getXmlObject(String xml, Class<T> cls) throws IOException {
return mapper.readValue(xml, cls);
}
public static void main(String[] args) throws Exception {
String xmlString = "<msg><head><Client>MyClient</Client><RoutingArea>Test</RoutingArea><ServerId>ABCXYZ123</ServerId></head><body><UserDetailResponse><UserDetail><Customer><CustomerId>1456342711975</CustomerId><BusinessUnit>TEST0000</BusinessUnit><Name><Salutation>U</Salutation><First>TROPICAL TAN</First></Name><Privacy>Y</Privacy></Customer><ItemList><Count>3</Count><Item><ServiceIdentifier>000001</ServiceIdentifier><BillingIdentifier>000001</BillingIdentifier></Item><Item><ServiceIdentifier>000002</ServiceIdentifier><BillingIdentifier>000002</BillingIdentifier></Item><Item><ServiceIdentifier>000003</ServiceIdentifier><BillingIdentifier>000003</BillingIdentifier></Item></ItemList></UserDetail></UserDetailResponse></body></msg>";
JacksonXmlModule jacksonXmlModule = new JacksonXmlModule();
jacksonXmlModule.setDefaultUseWrapper(false);
MyResponse myResponse = getXmlObject(xmlString, MyResponse.class);
System.out.println("XML Object: \n" + myResponse.toString());
ObjectMapper mapper = new ObjectMapper();
String str = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(myResponse);
System.out.println("JSON : \n" + str);
}
POJO:
public class MyResponse {
private Object head;
private Object body;
public Object getHead() {
return head;
}
public void setHead(Object head) {
this.head = head;
}
public Object getBody() {
return body;
}
public void setBody(Object body) {
this.body = body;
}
}
尽管输入 xml 字符串中的 ItemList 下有 3 个项目,但结果对象仅包含第 3 个项目。
结果:
JSON :
{
"head" : {
"Client" : "MyClient",
"RoutingArea" : "Test",
"ServerId" : "ABCXYZ123"
},
"body" : {
"UserDetailResponse" : {
"UserDetail" : {
"Customer" : {
"CustomerId" : "1456342711975",
"BusinessUnit" : "TEST0000",
"Name" : {
"Salutation" : "U",
"First" : "TROPICAL TAN"
},
"Privacy" : "Y"
},
"ItemList" : {
"Count" : "3",
"Item" : {
"ServiceIdentifier" : "000003",
"BillingIdentifier" : "000003"
}
}
}
}
}
}