Java XML JAXB Unserialize read(File file, Class typeParameterClass)

Here you can find the source of read(File file, Class typeParameterClass)

Description

Reads an XML file and returns the content as an object of the specified class.

License

Open Source License

Parameter

Parameter Description
file XML file.
typeParameterClass Class of the main object in the XML file.

Return

Content as an object of the specified class.

Declaration

@SuppressWarnings("unchecked")
public static <T> T read(File file, Class<T> typeParameterClass) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.io.ByteArrayInputStream;

import java.io.File;

import java.io.InputStream;

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

import javax.xml.bind.Unmarshaller;

public class Main {
    /**/*  w  ww  . java 2  s .c  o m*/
     * Reads an XML file and returns the content as an object of the specified class. 
     * @param file               XML file.
     * @param typeParameterClass   Class of the main object in the XML file.
     * @return                  Content as an object of the specified class.
     */
    @SuppressWarnings("unchecked")
    public static <T> T read(File file, Class<T> typeParameterClass) {
        T content = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(typeParameterClass);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            //jaxbUnmarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");

            content = (T) jaxbUnmarshaller.unmarshal(file);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return content;
    }

    @SuppressWarnings("unchecked")
    public static <T> T read(String input, Class<T> typeParameterClass) {
        T content = null;
        try {
            JAXBContext jaxbContext = JAXBContext.newInstance(typeParameterClass);

            Unmarshaller jaxbUnmarshaller = jaxbContext.createUnmarshaller();
            //jaxbUnmarshaller.setProperty(Marshaller.JAXB_ENCODING, "UTF-8");
            InputStream is = new ByteArrayInputStream(input.getBytes());
            content = (T) jaxbUnmarshaller.unmarshal(is);
        } catch (JAXBException e) {
            e.printStackTrace();
        }
        return content;
    }
}

Related

  1. parseJaxb(Class cls, InputStream in)
  2. parseXml(final Class klass, final Reader xmlReader)
  3. parseXML(String content, Class clazz)
  4. parseXmlFile(Class type, String filePath)
  5. read(Class cl, InputStream is)
  6. readComplexProperty(String name, List objects, String methodName)
  7. readExternal(InputStream inputStream, Class clazz)
  8. readJAXB(Class clazz, InputStream is)
  9. readJaxbObject(InputStream inputStream, Class jaxbModelClass)

  10. HOME | Copyright © www.java2s.com 2016