I want to convert a list of items inside of my payaload and convert them into a hashmap. Basically, what I have is an Item xml representation which have a list of ItemID. Each ItemID has an idType in it. However, inside my Item class, i want these ItemIDs to be represented as a Map.
HashMap<ItemIDType, ItemID>
The incoming payload will represent this as a list
<Item>...
<ItemIDs>
<ItemID type="external" id="XYZ"/>
<ItemID type="internal" id="20011"/>
</ItemIDs>
</Item>
but I want an adapter that will convert this into a HashMap
"external" => "xyz"
"internal" => "20011"
I am right now using a LinkedList
public class MapHashMapListAdapter extends XmlAdapter<LinkedList<ItemID>, Map<ItemIDType, ItemID>> {
public LinkedList<ItemID> marshal(final Map<ItemIDType, ItemID> v) throws Exception { ... }
public Map<ItemIDType, ItemID> unmarshal(final LinkedList<ItemID> v) throws Exception { ... }
}
but for some reason when my payload gets converted, it fails to convert the list into a hashmap. The incoming LinkedList of the method unmarshal is an empty list. Do you guys have any idea what I am doing wrong here? Do I need to create my own data type here to handle the LinkedList?
Instead of converting the Map
to a LinkedList
you need to convert it to a domain object.
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public final class MyMapAdapter extends
XmlAdapter<MyMapType,Map<Integer, String>> {
@Override
public MyMapType marshal(Map<Integer, String> arg0) throws Exception {
MyMapType myMapType = new MyMapType();
for(Entry<Integer, String> entry : arg0.entrySet()) {
MyMapEntryType myMapEntryType =
new MyMapEntryType();
myMapEntryType.key = entry.getKey();
myMapEntryType.value = entry.getValue();
myMapType.entry.add(myMapEntryType);
}
return myMapType;
}
@Override
public Map<Integer, String> unmarshal(MyMapType arg0) throws Exception {
HashMap<Integer, String> hashMap = new HashMap<Integer, String>();
for(MyMapEntryType myEntryType : arg0.entry) {
hashMap.put(myEntryType.key, myEntryType.value);
}
return hashMap;
}
}
For More Information
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With