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

Provisioning Cloud SQL with Private Service Connect Using Terraform & Accessing from Cloud Run with Spring Boot

In this post, we'll explore how to provision Cloud SQL instances with Private Service Connect (PSC) connectivity using Terraform and the...