How to serialize HashTable<String, String> to XML using JAXB?

≡放荡痞女 提交于 2019-11-30 09:40:53

You will need to create a wrapper class to hold onto the 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;
    }

}

Then you can do the following:

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

}

This will produce the following output:

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

Things to Note

  • JAXBContext is a thread-safe object and should be created once and reused.
  • Hashtable is synchronized, if you do not need this then using HashMap is the common replacement.
  • The convention is to start Java method names with a lower case letter.

Customizing the Mapping

You can use an XmlAdapter in JAXB to customize the mapping of any class. Below is an link to a post on my blog where I demonstrate how to do just that:

fruchtose

Unfortunately, JAXB is not able to directly serialize a Map or HashMap instance directly. Instead, you'll have to do some sort of translation from a Map into a list of entries that have a key and a value. Try looking into this Stack Overflow question and see if it can help you. This problem shows up a lot in Google, and the sad answer is that JAXB doesn't know how to serialize a Map.

Bah! If you had only googled on jaxb and hashmap you would have directly found this: http://download.oracle.com/javase/6/docs/api/javax/xml/bind/annotation/adapters/XmlAdapter.html

But, yes, I kind of agree that 'perplexion' is a good description of the feeling of the non-obviousness of the task.

While you might be familiar with C# reified generics, Java's generics are for compile time only, they go away at runtime. That's why, at runtime, even if you have an instance with established generics (Such as String for HashTable) at runtime those generics go away, so all you can do is obtain the class of the thing (HashTable here) and not the actual generic types (String here). In short: compile time Hashtable<String,String> becomes HashTable at runtime (or, to be totally pedantic HashTable<?,?>)

I think your best bet is to create an xml schema that reflects what you want and then run xjc on it. This way you have some control over what the xml will look like w/o getting into the guts of JaxB. http://download.oracle.com/docs/cd/E17802_01/webservices/webservices/docs/1.6/jaxb/xjc.html

You can then translate your HashTable to the generated object and pass it to this variation of your static method.

public static <T> String ObjectToXml(T object) throws JAXBException {
        JAXBContext jaxbContext = JAXBContext.newInstance(object.getClass());
        StringWriter writerTo = new StringWriter();
        Marshaller marshaller = jaxbContext.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.marshal(object, writerTo); 
        return writerTo.toString();
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!