All Downloads are FREE. Search and download functionalities are using the official Maven repository.

goja.core.kits.JaxbKit Maven / Gradle / Ivy

The newest version!
/*
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
 *
 * Copyright (c) 2013-2014 sagyf Yang. The Four Group.
 */
package goja.core.kits;

import com.google.common.base.Throwables;

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

import java.io.File;
import java.io.StringReader;
import java.io.StringWriter;

/**
 * Xml object互转. 
*/ public class JaxbKit { /** * string -> object */ @SuppressWarnings("unchecked") public static T unmarshal(String src, Class clazz) { T result = null; try { Unmarshaller avm = JAXBContext.newInstance(clazz).createUnmarshaller(); result = (T) avm.unmarshal(new StringReader(src)); } catch (JAXBException e) { Throwables.propagate(e); } return result; } @SuppressWarnings("unchecked") public static T unmarshal(File xmlFile, Class clazz) { T result = null; try { Unmarshaller avm = JAXBContext.newInstance(clazz).createUnmarshaller(); result = (T) avm.unmarshal(xmlFile); } catch (JAXBException e) { Throwables.propagate(e); } return result; } /** * object -> string * * @param jaxbElement jaxb element * @return string value. */ public static String marshal(Object jaxbElement) { StringWriter sw; try { Marshaller fm = JAXBContext.newInstance(jaxbElement.getClass()).createMarshaller(); fm.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true); sw = new StringWriter(); fm.marshal(jaxbElement, sw); } catch (JAXBException e) { throw new RuntimeException(e); } return sw.toString(); } }




© 2015 - 2025 Weber Informatics LLC | Privacy Policy