mar*_*ark 6 java xml hashtable jaxb
我试图使用JAXB序列化HashTable<String, String>到XML.我是Java的新手(来自C#),所以我对此任务感到困惑.
我看过以下代码:
public static <T> String ObjectToXml(T object, Class<T> classType) throws JAXBException
{
JAXBContext jaxbContext = JAXBContext.newInstance(classType);
StringWriter writerTo = new StringWriter();
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(object, writerTo); //create xml string from the input object
return writerTo.toString();
}
Run Code Online (Sandbox Code Playgroud)
这是如此调用:ObjectToXml(o, ClassOfO.class)但是HashTable<String, String>.class错了(我已经知道了).
那里的Java大师能告诉我如何调用这段代码吗?建议更简单的实现(当然还有调用示例)也是最受欢迎的.
谢谢.
您需要创建一个包装类来保存Hashtable:
package forum7534500;
import java.util.Hashtable;
import javax.xml.bind.annotation.XmlRootElement;
@XmlRootElement
public class Wrapper {
private Hashtable<String, String> hashtable;
public Hashtable<String, String> getHashtable() {
return hashtable;
}
public void setHashtable(Hashtable<String, String> hashtable) {
this.hashtable = hashtable;
}
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以执行以下操作:
package forum7534500;
import java.io.StringWriter;
import java.util.Hashtable;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
public class Demo {
public static void main(String[] args) throws Exception {
JAXBContext jc = JAXBContext.newInstance(Wrapper.class);
Wrapper wrapper = new Wrapper();
Hashtable<String, String> hashtable = new Hashtable<String,String>();
hashtable.put("foo", "A");
hashtable.put("bar", "B");
wrapper.setHashtable(hashtable);
System.out.println(objectToXml(jc, wrapper));
}
public static String objectToXml(JAXBContext jaxbContext, Object object) throws JAXBException
{
StringWriter writerTo = new StringWriter();
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(object, writerTo); //create xml string from the input object
return writerTo.toString();
}
}
Run Code Online (Sandbox Code Playgroud)
这将产生以下输出:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<wrapper>
<hashtable>
<entry>
<key>bar</key>
<value>B</value>
</entry>
<entry>
<key>foo</key>
<value>A</value>
</entry>
</hashtable>
</wrapper>
Run Code Online (Sandbox Code Playgroud)
注意事项
JAXBContext 是一个线程安全的对象,应该创建一次并重用.Hashtable是同步的,如果你不需要这个,那么使用HashMap是常见的替代品.自定义映射
您可以XmlAdapter在JAXB中使用a 来自定义任何类的映射.以下是我博客上帖子的链接,我将演示如何做到这一点: