[英]How to marshal map to xml without tag value
I have a HashMap which I want to convert to XML: 我有一个HashMap,我想转换为XML:
@XmlJavaTypeAdapter(OrdersAdapter.class)
private Map<Long, Order> orders = new LinkedHashMap<Long, Order>();
By default map is converted to <entry><key></key><value></value><entry>
, but I wanted to get XML, where key is attribute and there is no value tag. 默认情况下,map会转换为
<entry><key></key><value></value><entry>
,但我想获取XML,其中key是attribute,没有值标记。 Something like this: 像这样的东西:
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
<productsMap>
<orders>
<order orderId="1">
<prodId>123</prodId>
<price>1</price>
</order>
<order orderId="2">
<prodId>15</prodId>
<price>10</price>
</order>
</orders>
</productsMap>
Using my program from github: https://github.com/pfryn/simpleTestProject/tree/master/src/pl/shop , now I am able to generate xml like this: 使用我的程序来自github: https : //github.com/pfryn/simpleTestProject/tree/master/src/pl/shop ,现在我能够像这样生成xml:
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
<productsMap>
<orders>
<order orderId="1">
<value>
<prodId>123</prodId>
<price>1</price>
</value>
</order>
<order orderId="2">
<value>
<prodId>15</prodId>
<price>10</price>
</value>
</order>
</orders>
</productsMap>
Do you know how to avoid "value" tag? 你知道如何避免“价值”标签吗?
OrderType 订单类型
public class OrderType {
public List<Order> order =
new ArrayList<Order>();
}
OrdersAdapter OrdersAdapter
public class OrdersAdapter extends XmlAdapter<OrderType, Map<Long, Order>> {
@Override
public Map<Long, Order> unmarshal(OrderType v) throws Exception {
Map<Long, Order> hashMap = new HashMap<Long, Order>();
for (Order myEntryType : v.order) {
hashMap.put(myEntryType.orderId, myEntryType);
}
return hashMap;
}
@Override
public OrderType marshal(Map<Long, Order> map) throws Exception {
OrderType ordType = new OrderType();
for (Entry<Long, Order> entry : map.entrySet()) {
Order ordEntryType =
new Order();
ordEntryType.orderId = entry.getKey();
ordEntryType.price = entry.getValue().price;
ordEntryType.prodId = entry.getValue().prodId;
ordType.order.add(ordEntryType);
}
return ordType;
}
}
Order 订购
public class Order {
public Order(){
super();
}
public Order(Long prodId, BigDecimal price) {
this();
this.prodId = prodId;
this.price = price;
}
@XmlAttribute
public Long orderId;
public Long prodId;
public BigDecimal price;
}
OUTPUT XML 输出XML
<?xml version="1.0" encoding="UTF-16" standalone="yes"?>
<productsMap>
<orders>
<order orderId="1">
<prodId>123</prodId>
<price>1</price>
</order>
<order orderId="2">
<prodId>15</prodId>
<price>10</price>
</order>
</orders>
</productsMap>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.