Tuesday, March 20, 2018

Generic method Marshalling and Unmarshalling JAXB

I share example JAXB.

public static  <T> String convertObjectToXML(T object) 
{
        try {

            StringWriter stringWriter = new StringWriter();
            JAXBContext context = JAXBContext.newInstance(object.getClass());
            Marshaller marshaller = context.createMarshaller();
            marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, Boolean.TRUE);
            marshaller.marshal(object, stringWriter);
            return stringWriter.toString();
        } 
        catch (JAXBException e){
         throw new RuntimeException(String.format("Exception while marshalling: %s", e.getMessage()));
        }
   }
 
    @SuppressWarnings("unchecked")
  public static <T> T convertXMLToObject(Class<T> clazz, String xml) 
    {
        try {

            JAXBContext context = JAXBContext.newInstance(clazz);
            Unmarshaller um = context.createUnmarshaller();
            return (T) um.unmarshal(new StringReader(xml));
        } 
        catch (JAXBException je){
            throw new RuntimeException(String.format("Exception while Unmarshaller: %s", je.getMessage()));
        }
    }

@SuppressWarnings("unchecked")
public static <T> T convertXMLToObject(Class<T> clazz, InputStream file) {
   
   
    try {
    JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
T obj = (T) jaxbUnmarshaller.unmarshal(file);
return obj;

} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
throw new RuntimeException(String.format("Exception while Unmarshaller: %s", e.getMessage()));
}
    }

No comments:

Post a Comment

Virtual Threads in Java 21: Simplified Concurrency for Modern Applications

  With Java 21, Virtual Threads have redefined how we approach concurrency, offering a lightweight and efficient way to handle parallel and ...