Java JAXB在没有适配器的情况下编组映射
我有一个映射,我想将它封送到XML。只要有大量不同类型的映射,我就不想为每个映射编写自定义XmlAdapter。 对于用作键的所有类,我都有XmlAdapters。当我单独封送这些类时,它们工作得很好,但是当我封送映射时,键就被忽略了。我得到的只是以下XML:Java JAXB在没有适配器的情况下编组映射,java,jaxb,Java,Jaxb,我有一个映射,我想将它封送到XML。只要有大量不同类型的映射,我就不想为每个映射编写自定义XmlAdapter。 对于用作键的所有类,我都有XmlAdapters。当我单独封送这些类时,它们工作得很好,但是当我封送映射时,键就被忽略了。我得到的只是以下XML: <entry> <key/> <value> <id>1</id> <property>something</p
<entry>
<key/>
<value>
<id>1</id>
<property>something</property>
</value>
</entry>
1.
某物
我想要的是:
<entry>
<key>
<property>something</property>
</key>
<value>
<id>1</id>
<property>something</property>
</value>
</entry>
某物
1.
某物
有没有一种方法可以在不为每个映射编码自定义XmlAdapter的情况下获得所需的结果?使用JAXB和
java.util.map
没有什么特殊的需要。下面我将用一个例子来演示
Java模型
Foo
import java.util.*;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Foo {
private Map<Bar, Bar> bars = new HashMap<Bar, Bar>();
public Map<Bar, Bar> getBars() {
return bars;
}
public void setBars(Map<Bar, Bar> bars) {
this.bars = bars;
}
}
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Foo.class);
Foo foo = new Foo();
Bar bar1 = new Bar();
bar1.setBaz("Hello");
Bar bar2 = new Bar();
bar2.setBaz("World");
foo.getBars().put(bar1, bar2);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(foo, System.out);
}
}
演示代码
演示
import java.util.*;
import javax.xml.bind.annotation.*;
@XmlRootElement
public class Foo {
private Map<Bar, Bar> bars = new HashMap<Bar, Bar>();
public Map<Bar, Bar> getBars() {
return bars;
}
public void setBars(Map<Bar, Bar> bars) {
this.bars = bars;
}
}
import javax.xml.bind.*;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Foo.class);
Foo foo = new Foo();
Bar bar1 = new Bar();
bar1.setBaz("Hello");
Bar bar2 = new Bar();
bar2.setBaz("World");
foo.getBars().put(bar1, bar2);
Marshaller marshaller = jc.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(foo, System.out);
}
}
输出
你好
世界
更多信息
我在我的博客上写了更多关于JAXB和java.util.Map
: