Java XML JAXB String to Object convertToObject(Class clazz, InputStream inputStream)

Here you can find the source of convertToObject(Class clazz, InputStream inputStream)

Description

XML to Object

License

Apache License

Parameter

Parameter Description
T a parameter
clazz a parameter
inputStream a parameter

Declaration

public static <T> T convertToObject(Class<T> clazz, InputStream inputStream) 

Method Source Code


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

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

import javax.xml.bind.Unmarshaller;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

public class Main {
    private static final ThreadLocal<Map<Class<?>, Unmarshaller>> uMapLocal = new ThreadLocal<Map<Class<?>, Unmarshaller>>() {
        @Override//from w  ww  .  java 2s .  com
        protected Map<Class<?>, Unmarshaller> initialValue() {
            return new HashMap<>();
        }
    };

    /**
     * XML to Object
     * @param <T>
     * @param clazz
     * @param xml
     * @return
     */
    public static <T> T convertToObject(Class<T> clazz, String xml) {
        return convertToObject(clazz, new StringReader(xml));
    }

    /**
     * XML to Object
     * @param <T>
     * @param clazz
     * @param inputStream
     * @return
     */
    public static <T> T convertToObject(Class<T> clazz, InputStream inputStream) {
        return convertToObject(clazz, new InputStreamReader(inputStream));
    }

    /**
     * XML to Object
     * @param <T>
     * @param clazz
     * @param reader
     * @return
     */
    @SuppressWarnings("unchecked")
    public static <T> T convertToObject(Class<T> clazz, Reader reader) {
        try {
            Map<Class<?>, Unmarshaller> uMap = uMapLocal.get();
            if (!uMap.containsKey(clazz)) {
                JAXBContext jaxbContext = JAXBContext.newInstance(clazz);
                Unmarshaller unmarshaller = jaxbContext.createUnmarshaller();
                uMap.put(clazz, unmarshaller);
            }
            return (T) uMap.get(clazz).unmarshal(reader);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Related

  1. convertStringToJAXB(String str)
  2. convertToJAXBException(String msg, Throwable e)
  3. convertToXmlFile(File file, Object source, Class... type)
  4. convertXmlFileToObject(Class clazz, String xmlPath)
  5. convertXmlToObj(Class clazz, String xmlStr)
  6. convertXMLToObject(byte[] data, Class clazz)