注意: 我是EclipseLink JAXB (MOXy)负责人,也是JAXB (JSR-222)专家组的成员。
您可以利用 MOXy 的@XmlPath
扩展来支持您的用例。
信息
package forum11956071;
import java.util.Map;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
import org.eclipse.persistence.oxm.annotations.XmlPath;
@XmlRootElement
@XmlAccessorType(XmlAccessType.FIELD)
class Info {
@XmlJavaTypeAdapter(MapAdapter.class)
@XmlPath(".")
private Map<Integer,String> map;
}
地图适配器
package forum11956071;
import java.util.*;
import java.util.Map.Entry;
import javax.xml.bind.annotation.*;
import javax.xml.bind.annotation.adapters.XmlAdapter;
public class MapAdapter extends XmlAdapter<MapAdapter.AdaptedMap, Map<Integer, String>>{
public static class AdaptedMap {
public List<Item> item = new ArrayList<Item>();
}
public static class Item {
@XmlAttribute Integer key;
@XmlValue String value;
}
@Override
public AdaptedMap marshal(Map<Integer, String> map) throws Exception {
AdaptedMap adaptedMap = new AdaptedMap();
for(Entry<Integer, String> entry : map.entrySet()) {
Item item = new Item();
item.key = entry.getKey();
item.value = entry.getValue();
adaptedMap.item.add(item);
}
return adaptedMap;
}
@Override
public Map<Integer, String> unmarshal(AdaptedMap adaptedMap) throws Exception {
Map<Integer, String> map = new HashMap<Integer, String>();
for(Item item : adaptedMap.item) {
map.put(item.key, item.value);
}
return map;
}
}
jaxb.properties
要将 MOXy 指定为您的 JAXB 提供程序,您需要jaxb.properties
在与您的域模型相同的包中拥有一个名为 file 的文件,其中包含以下条目(请参阅:http ://blog.bdoughan.com/2011/05/specifying-eclipselink-moxy- as-your.html:
javax.xml.bind.context.factory=org.eclipse.persistence.jaxb.JAXBContextFactory
演示
package forum11956071;
import java.io.File;
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Info.class);
Unmarshaller unmarshaller = jc.createUnmarshaller();
File xml = new File("src/forum11956071/input.xml");
Info info = (Info) unmarshaller.unmarshal(xml);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(info, System.out);
}
}
输入.xml/输出
<?xml version="1.0" encoding="UTF-8"?>
<info>
<item key="1">value1</item>
<item key="2">value2</item>
</info>