gpt4 book ai didi

java - 如何使用 JAXB 将 HashTable 序列化为 XML?

转载 作者:塔克拉玛干 更新时间:2023-11-03 04:47:48 24 4
gpt4 key购买 nike

我正在尝试使用 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();
}

像这样调用: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;
}

}

然后您可以执行以下操作:

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();
}

}

这将产生以下输出:

<?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>

注意事项

  • JAXBContext 是线程安全的对象,应创建一次并重复使用。
  • Hashtable 是同步的,如果您不需要它,则使用 HashMap 是常见的替代品。
  • 约定是 Java 方法名称以小写字母开头。

自定义映射

您可以在 JAXB 中使用 XmlAdapter 来自定义任何类的映射。下面是我博客上一篇文章的链接,我在其中演示了如何做到这一点:

关于java - 如何使用 JAXB 将 HashTable<String, String> 序列化为 XML?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7534500/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com