How to marshal a map to xml without tag value
I have a HashMap that I want to convert to XML:
@XmlJavaTypeAdapter(OrdersAdapter.class)
private Map<Long, Order> orders = new LinkedHashMap<Long, Order>();
By default, the map is converted to <entry><key></key><value></value><entry>
, but I want to get XML where the key is an attribute and there is no value sign. Something like that:
<?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 can generate xml like this:
<?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 the "value" tag?
+3
source to share
1 answer
OrderType
public class OrderType {
public List<Order> order =
new ArrayList<Order>();
}
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;
}
XML OUTPUT
<?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>
+3
source to share