I am trying to use JAXB to serialize a HashTable<String, String> to XML. I am very new to Java (came from C#), so I am kinda perplexed by this task.
I have seen the following code:
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();
}
Which is invoked like so: ObjectToXml(o, ClassOfO.class), but HashTable<String, String>.class is wrong (that I already know).
Can Java gurus out there show me how to invoke this code? Proposing a simpler implementation (along with an invocation example, of course) is most welcome as well.
Thanks.
You will need to create a wrapper class to hold onto the
Hashtable:Then you can do the following:
This will produce the following output:
Things to Note
JAXBContextis a thread-safe object and should be created once and reused.Hashtableis synchronized, if you do not need this then usingHashMapis the common replacement.Customizing the Mapping
You can use an
XmlAdapterin 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: