Java XML JAXB String to Object toObject(String xml, Class c)

Here you can find the source of toObject(String xml, Class c)

Description

to Object

License

Apache License

Declaration

@SuppressWarnings("unchecked")
public static <T> T toObject(String xml, Class<T> c) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.StringReader;

import javax.xml.bind.JAXBContext;

import javax.xml.transform.stream.StreamSource;

public class Main {

    @SuppressWarnings("unchecked")
    public static <T> T toObject(String xml, Class<T> c) {
        if (xml == null || "".equals(xml.trim())) {
            return null;
        }//from   w  w  w  . j ava 2s.co  m
        StringReader reader = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            javax.xml.bind.Unmarshaller unmarshaller = context.createUnmarshaller();
            reader = new StringReader(xml);
            T result = (T) unmarshaller.unmarshal(new StreamSource(reader));
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            ;
            throw new RuntimeException(e.getMessage(), e);
        } finally {
            if (reader != null) {
                try {
                    reader.close();
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new RuntimeException(e);
                }
            }
        }
    }
}

Related

  1. fromXml(String xml, Class type)
  2. fromXML(String xml, Class valueType)
  3. getXmlObject(String xml, Class cls)
  4. stringToObject(String s, Class theclass)
  5. toObject(Class className, String strXml)
  6. toObject(String xml, Class clazz)
  7. xml2obj(final Class cls, final String xml)
  8. xml2Object(String content, Class valueType)
  9. Xml2Object(String xmlString, Class clazz)