jaxb 简单的对象与xml相互转换

来源:互联网 发布:mtkoala男友知乎 编辑:程序博客网 时间:2024/05/21 07:58

/** *  */import java.io.File;import java.io.IOException;import java.io.StringReader;import java.io.StringWriter;import javax.xml.bind.JAXBContext;import javax.xml.bind.JAXBException;import javax.xml.bind.Marshaller;import javax.xml.bind.Unmarshaller;import org.apache.commons.io.FileUtils;/** *  * @author zhangdapeng * @version 1.0,2014年7月18日 * @since 1.0 */public class JaxbUtil {/** *  * @param obj * @param encoding * @return * @throws JAXBException */public static String convertObjectToXml(Object obj, String encoding) throws JAXBException {String result = null;JAXBContext context = JAXBContext.newInstance(obj.getClass());Marshaller marshaller = context.createMarshaller();marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);marshaller.setProperty(Marshaller.JAXB_ENCODING, encoding);StringWriter writer = new StringWriter();marshaller.marshal(obj, writer);result = writer.toString();return result;}/** *  * @param xml * @param c * @return * @throws JAXBException  */@SuppressWarnings("unchecked")public static <T> T convertXmlToObject(String xml, Class<T> c) throws JAXBException {T t = null;JAXBContext context = JAXBContext.newInstance(c);Unmarshaller unmarshaller = context.createUnmarshaller();StringReader sr = new StringReader(xml);//// int i;// do {// i = sr.read();// char c1 = (char) i;// System.out.print(c1);// } while (i != -1);t = (T) unmarshaller.unmarshal(sr);return t;}public static void main(String[] args) throws IOException, JAXBException {ThreadConfiguration test = new ThreadConfiguration();test.setCore(10);String c = JaxbUtil.convertObjectToXml(test, "utf-8");System.out.println(c);File file = new File("E:/workspace/testgs-maven/src/main/java/thread.xml");String xmlStr = FileUtils.readFileToString(file, "UTF-8");test = JaxbUtil.convertXmlToObject(xmlStr, ThreadConfiguration.class);System.out.println(test.getKeepAliveTime());}}

0 0
原创粉丝点击