I have an XML to unmarshall:
<?xml version="1.0" encoding="UTF-8"?>
<ROW id='1'>
<MOBILE>9831138683</MOBILE>
<A>1</A>
<B>2</B>
</ROW>
I want to map it to a class:
import java.util.*;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
public class ROW {
@XmlPath(".")
@XmlJavaTypeAdapter(MapAdapter.class)
private Map<String, Integer> map = new HashMap<String, Integer>();
@XmlAttribute
private int id;
@XmlElement(name = "MOBILE")
private int mobileNo;
}
For this I tried the bdoughan blog where it uses @XmlVariableNode("key")
:
MapAdapter:
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import javax.xml.bind.annotation.XmlTransient;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.XmlAdapter;
import org.eclipse.persistence.oxm.annotations.XmlVariableNode;
public class MapAdapter extends XmlAdapter<MapAdapter.AdaptedMap, Map<String, String>> {
public static class AdaptedMap {
@XmlVariableNode("key")
List<AdaptedEntry> entries = new ArrayList<AdaptedEntry>();
}
public static class AdaptedEntry {
@XmlTransient
public String key;
@XmlValue
public String value;
}
@Override
public AdaptedMap marshal(Map<String, String> map) throws Exception {
AdaptedMap adaptedMap = new AdaptedMap();
for(Entry<String, String> entry : map.entrySet()) {
AdaptedEntry adaptedEntry = new AdaptedEntry();
adaptedEntry.key = entry.getKey();
adaptedEntry.value = entry.getValue();
adaptedMap.entries.add(adaptedEntry);
}
return adaptedMap;
}
@Override
public Map<String, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
List<AdaptedEntry> adaptedEntries = adaptedMap.entries;
Map<String, String> map = new HashMap<String, String>(adaptedEntries.size());
for(AdaptedEntry adaptedEntry : adaptedEntries) {
map.put(adaptedEntry.key, adaptedEntry.value);
}
return map;
}
}
Using this approach all the keys(MOBILE, id, A, B
) are mapped inside the Map
. I want to unmarshall such that all defined attributes the id
, MOBILE
are mapped to their attributes in POJO and rest all are mapped to Map
.
How can this be achieved ?