栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

如何序列化HashTable 使用JAXB转换为XML?

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

如何序列化HashTable 使用JAXB转换为XML?

您将需要创建一个包装器类以保留

Hashtable

package forum7534500;import java.util.Hashtable;import javax.xml.bind.annotation.XmlRootElement;@XmlRootElementpublic 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方法名称。

自定义映射

您可以

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

  • http://blog.bdoughan.com/2010/07/xmladapter-jaxbs-secret-weapon.html


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/596014.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号