Java XML JAXB Serialize serialiseObject(Object obj, Class objclass)

Here you can find the source of serialiseObject(Object obj, Class objclass)

Description

serialise Object

License

Open Source License

Declaration

static public String serialiseObject(Object obj, Class<?> objclass) throws JAXBException 

Method Source Code

//package com.java2s;
//  sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is

import java.io.StringWriter;

import java.util.HashMap;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;

public class Main {
    private static HashMap<String, JAXBContext> jaxbContentCache = new HashMap<String, JAXBContext>();

    static public String serialiseObject(Object obj, Class<?> objclass) throws JAXBException {
        JAXBContext jaxbContext = getJAXBContext(objclass);
        Marshaller m = jaxbContext.createMarshaller();
        StringWriter w = new StringWriter();
        m.marshal(obj, w);/*from   w w w  .java2s.  c  o  m*/
        String xmlString = w.toString();
        return xmlString;
    }

    /** Serialise the object to an XML string
     * @param obj the object to be serialised
     * @param objclass the class of the object to be serialised
     * @return an XML string representing the object, or null if the object couldn't be serialised
     * @throws JAXBException 
     */

    static private JAXBContext getJAXBContext(Class<?> objclass) throws JAXBException {
        JAXBContext jaxbContext;
        if (jaxbContentCache.containsKey(objclass.getName())) {
            jaxbContext = jaxbContentCache.get(objclass.getName());
        } else {
            jaxbContext = JAXBContext.newInstance(objclass);
            jaxbContentCache.put(objclass.getName(), jaxbContext);
        }
        return jaxbContext;
    }
}

Related

  1. saveModel(JAXBElement model, String packageName)
  2. saveObject(Path path, T object)
  3. saveObject(T object, Class typeClass, URL path)
  4. saveToFile(String fileName, T obj)
  5. saveXML(Object object, String fileNamePath, Boolean append)
  6. serialize(final Object object)
  7. serialize(JAXBElement emp, Class clazz, OutputStream out)
  8. serialize(JAXBElement object)
  9. serialize(Object o, OutputStream os, Boolean format)