Skip to content

Instantly share code, notes, and snippets.

@iqbmo04
Forked from madan712/Test.java
Created July 22, 2020 13:54
Show Gist options
  • Select an option

  • Save iqbmo04/9295ab1b3759156ecfb72547259ee126 to your computer and use it in GitHub Desktop.

Select an option

Save iqbmo04/9295ab1b3759156ecfb72547259ee126 to your computer and use it in GitHub Desktop.
Marshalling and unmarshalling of Hashtable using Holder class
import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.Hashtable;
import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
public class Test {
public static void main(String[] args) throws JAXBException {
Hashtable<String, String> htmlColorCode = new Hashtable<String, String>();
htmlColorCode.put("red", "FF0000");
htmlColorCode.put("green", "00FF00");
htmlColorCode.put("blue", "0000FF");
MapHolder holder = new MapHolder();
holder.setHtmlColorCode(htmlColorCode);
System.out.println("--Marshalling--");
String listXML = marshalIt(holder);
System.out.println(listXML);
System.out.println("--Unmarshalling--");
MapHolder newHolder = (MapHolder) unmarshalIt(MapHolder.class, listXML);
System.out.println(newHolder.getHtmlColorCode());
}
public static String marshalIt(Object objectName) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(objectName.getClass());
Marshaller marshaller = jaxbContext.createMarshaller();
// For Pretty printing output
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
StringWriter writer = new StringWriter();
marshaller.marshal(objectName, writer);
return writer.toString();
}
public static Object unmarshalIt(Class<?> className, String xml) throws JAXBException {
JAXBContext jaxbContext = JAXBContext.newInstance(className);
Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
StringReader reader = new StringReader(xml);
return unmarshaller.unmarshal(reader);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment