看起来你几乎一切都正确,但你的问题是上下文可能不知道如何处理你定义的枚举类。
我能够构建一小组类来生成您想要的输出,而无需任何特殊的枚举注释。
编辑:因此,在进一步评估问题后,特别是与解组相关的问题,我修改了测试以尝试解组粘贴在您的问题描述中的 XML(用 <Foo></Foo> 标签包装)并重新-将获得的对象编组到 System.out 以验证一切正常。
我创建了一个名为“MyXml.xml”的文件,其内容如下(从上面):
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Foo>
<table>
<entry>
<key xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">Name</key>
<value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">Test</value>
</entry>
<entry>
<key xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">Type</key>
<value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:type="myEnum">ONE</value>
</entry>
</table>
</Foo>
然后,使用像这样注释的 Foo 类:
@XmlRootElement(name = "Foo")
@XmlAccessorType(XmlAccessType.FIELD)
public class Foo implements Serializable {
private static final long serialVersionUID = 1L;
public Foo() {}
// wrap your map in a table tag
@XmlElementWrapper(name = "table")
// the entry will be the tag used to enclose the key,value pairs
@XmlElement(name="entry")
Map<Object, Object> myMap = new HashMap<Object, Object>();
public Map<Object,Object> getMyMap() {
return myMap;
}
}
简单的枚举类,不需要注解:
public enum MyEnum {
ONE, TWO, THREE;
}
这个测试:
public class Test {
public static void main(String[] args) throws Exception {
// create your context, and make sure to tell it about your enum class
JAXBContext context = JAXBContext.newInstance(new Class[]{Foo.class,MyEnum.class});
// create the unmarshaller
Unmarshaller unmarshaller = context.createUnmarshaller();
// try to unmarshal the XML into a Foo object
Foo f = (Foo) unmarshaller.unmarshal(new File("MyXml.xml"));
// if it worked, try to write it back out to System.out and verify everything worked!
if ( f != null) {
Marshaller m = context.createMarshaller();
m.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
m.marshal(f, System.out);
}
}
}
产生以下输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Foo>
<table>
<entry>
<key xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">Type</key>
<value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:type="myEnum">ONE</value>
</entry>
<entry>
<key xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">Name</key>
<value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">Test</value>
</entry>
</table>
</Foo>
如您所见,不需要额外的 Enum 管理,并且观察到了正确的输出。
希望这会有所帮助。