理念是拥有一个具有成员“value”的类,它可以包含简单类型,如String或Integer,还有一个简单类型的Map,连接到一个布尔值(例如,HashMap
这是一个“工作”的例子,它显示了我想要做的事情:
package test;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import javax.xml.bind.JAXB;
import javax.xml.bind.annotation.XmlElement;
import javax.xml.bind.annotation.XmlElements;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlSeeAlso;
@XmlRootElement
public class TestJAXB {
public static void main(String[] args) {
TestJAXB test = new TestJAXB();
JAXB.marshal(test, new File("foo.xml"));
}
Container one;
Container two;
Container three;
Container four;
public TestJAXB() {
this.one = new Container("foo");
this.two = new Container("42");
this.three = new Container(true);
HashMap<Object, Boolean> map = new HashMap<Object, Boolean>();
map.put("foo", false);
map.put("bar", false);
map.put("foobar", true);
this.four = new Container(map);
}
@XmlElement
public Container getOne() {
return one;
}
public void setOne(Container one) {
this.one = one;
}
@XmlElement
public Container getTwo() {
return two;
}
public void setTwo(Container two) {
this.two = two;
}
@XmlElement
public Container getThree() {
return three;
}
public void setThree(Container three) {
this.three = three;
}
@XmlElement
public Container getFour() {
return four;
}
public void setFour(Container four) {
this.four = four;
}
}
@XmlRootElement
@XmlSeeAlso(HashMap.class)
class Container {
Map<Object, Boolean> value = null;
boolean wasMap = false;
protected Container() {
}
protected Container(Object value) {
this.setValue(value);
}
@XmlElements({ @XmlElement(name = "string", type = String.class), @XmlElement(name = "bool", type = Boolean.class), @XmlElement(name = "int", type = Integer.class), })
public Object getValue() {
if (wasMap) {
return value;
} else {
return value.keySet().toArray()[0];
}
}
@SuppressWarnings("unchecked")
public void setValue(Object value) {
if (value instanceof Map) {
this.value = (Map<Object, Boolean>) value;
this.wasMap = true;
} else {
this.value = new HashMap<Object, Boolean>();
this.value.put(value, false);
this.wasMap = false;
}
}
}
嗯,简单的类型被编组到精细的xml,但地图的元素保持空白:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<testJAXB>
<four>
<string xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="hashMap"/>
</four>
<one>
<string>foo</string>
</one>
<three>
<bool>true</bool>
</three>
<two>
<string>42</string>
</two>
</testJAXB>
我做错了什么?我该怎么办?