• Bean转XML


    将实体类转为XML

    pom依赖

              <dependency>
    			<groupId>com.thoughtworks.xstream</groupId>
    			<artifactId>xstream</artifactId>
    			<version>1.4.10</version>
    		</dependency>
    		<dependency>
    		    <groupId>org.apache.commons</groupId>
    		    <artifactId>commons-lang3</artifactId>
    		    <version>3.8</version>
    		</dependency>
    		<dependency>
    		    <groupId>joda-time</groupId>
    		    <artifactId>joda-time</artifactId>
    		    <version>2.10</version>
    		</dependency>
    

    XstreamDateConverter.java

    package com.jmev.mobile.utils;
    
    import java.util.Date;
    
    import org.joda.time.DateTime;
    import org.joda.time.format.DateTimeFormat;
    import org.joda.time.format.DateTimeFormatter;
    
    import com.thoughtworks.xstream.converters.Converter;
    import com.thoughtworks.xstream.converters.MarshallingContext;
    import com.thoughtworks.xstream.converters.UnmarshallingContext;
    import com.thoughtworks.xstream.io.HierarchicalStreamReader;
    import com.thoughtworks.xstream.io.HierarchicalStreamWriter;
    
    public class XstreamDateConverter implements Converter {
    	
    	// 支持转换的日期格式
    	private static final DateTimeFormatter[] ACCEPT_DATE_FORMATS = {
    		DateTimeFormat.forPattern("yyyy-MM-dd"),
    		DateTimeFormat.forPattern("yyyy-MM"),
    		DateTimeFormat.forPattern("yyyy-MM-dd HH:mm:ss"),
    		DateTimeFormat.forPattern("yyyy/MM/dd")
    	};
    
    	/* (non-Javadoc)
    	 * @see com.thoughtworks.xstream.converters.ConverterMatcher#canConvert(java.lang.Class)
    	 */
    	@SuppressWarnings("rawtypes")
    	public boolean canConvert(Class type) {
    		return Date.class == type;
    	}
    
    	/* (non-Javadoc)
    	 * @see com.thoughtworks.xstream.converters.Converter#marshal(java.lang.Object, com.thoughtworks.xstream.io.HierarchicalStreamWriter, com.thoughtworks.xstream.converters.MarshallingContext)
    	 */
    	public void marshal(Object source, HierarchicalStreamWriter writer, MarshallingContext context) {
    		
    	}
    
    	/* (non-Javadoc)
    	 * @see com.thoughtworks.xstream.converters.Converter#unmarshal(com.thoughtworks.xstream.io.HierarchicalStreamReader, com.thoughtworks.xstream.converters.UnmarshallingContext)
    	 */
    	public Object unmarshal(HierarchicalStreamReader reader, UnmarshallingContext context) {
    		if (reader.getValue() == null || "".equals(reader.getValue())) {
    			return null;
    		}
    		DateTime dt = null;
    		
    		for (DateTimeFormatter format : ACCEPT_DATE_FORMATS) {
    			try {
    				// 遍历日期支持格式,进行转换
    				dt = format.parseDateTime(reader.getValue());
    				break;
    			} catch (Exception e) {
    				continue;
    			}
    		}
    		
    		return dt == null ? null : dt.getMillis();
    	}
    
    }
    

    XstreamUtil.java

    package com.jmev.mobile.utils;
    
    import java.io.File;
    import java.io.FileInputStream;
    import java.io.InputStream;
    import java.io.StringWriter;
    import java.io.Writer;
    
    import org.apache.commons.lang3.CharEncoding;
    import org.apache.commons.lang3.StringUtils;
    
    import com.jmev.mobile.entity.get.Response_info;
    import com.jmev.mobile.entity.get.Svc_result;
    import com.thoughtworks.xstream.XStream;
    import com.thoughtworks.xstream.io.naming.NoNameCoder;
    import com.thoughtworks.xstream.io.xml.CompactWriter;
    import com.thoughtworks.xstream.io.xml.DomDriver;
    
    /**
     * Xstream模式,bean 与 XML 互转处理类
     * 
     * @author ghw
     * 
     */
    public class XstreamUtil {
    
    	public static void main(String[] args) {
    		Svc_result svc_result = new Svc_result();
    		svc_result.setVer("2.0.0");
    		Response_info response_info = new Response_info();
    		response_info.setGwid("MAS请求消息流水号");
    		response_info.setRetcode("返回码");
    		response_info.setRetmesg("返回描述");
    		svc_result.setResponse_info(response_info);
    		System.out.println(toPrettyXML(svc_result, UTF8));
    	}
    
    	public static String UTF8 = "<?xml version="1.0" encoding="UTF-8"?>";
    
    	public static String GBK = "<?xml version="1.0" encoding="GBK"?>";
    
    	public static String GB18030 = "<?xml version="1.0" encoding="GB18030"?>";
    
    	public static String NEWLINE = "
    ";
    
    	/**
    	 * bean -> xml 格式化显示
    	 * 
    	 * @return
    	 */
    	public static String toPrettyXML(Object obj, String xmlHead) {
    		xmlHead = StringUtils.isBlank(xmlHead) ? UTF8 : xmlHead;
    		XStream xs = new XStream(new DomDriver(CharEncoding.UTF_8, new NoNameCoder()));
    		xs.autodetectAnnotations(true);
    		Writer writer = new StringWriter();
    		xs.toXML(obj, writer);
    		return xmlHead + NEWLINE + writer.toString();
    	}
    
    	/**
    	 * bean -> xml
    	 * 
    	 * @return
    	 */
    	public static String toXML(Object obj, String xmlHead) {
    		xmlHead = StringUtils.isBlank(xmlHead) ? UTF8 : xmlHead;
    
    		XStream xs = new XStream(new DomDriver(CharEncoding.UTF_8, new NoNameCoder()));
    		xs.autodetectAnnotations(true);
    		Writer writer = new StringWriter();
    		xs.marshal(obj, new CompactWriter(writer, new NoNameCoder()));
    
    		return xmlHead + writer.toString();
    	}
    
    	/**
    	 * xml -> bean
    	 * 
    	 * @param xmlStr
    	 * @return
    	 */
    	public static Object toBean(String xmlStr, Object obj) {
    
    		XStream xs = new XStream(new DomDriver(UTF8, new NoNameCoder()));
    		xs.autodetectAnnotations(true);
    		xs.registerConverter(new XstreamDateConverter());
    		Writer writer = new StringWriter();
    		xs.marshal(obj, new CompactWriter(writer, new NoNameCoder()));
    
    		return xs.fromXML(xmlStr, obj);
    	}
    
    	/**
    	 * xml -> bean
    	 * 
    	 * @param xmlStr
    	 * @return
    	 */
    	@SuppressWarnings("unchecked")
    	public static <T> T toBean(String xmlStr, Class<T> cls) {
    
    		XStream xstream = new XStream(new DomDriver(UTF8, new NoNameCoder()));
    		xstream.registerConverter(new XstreamDateConverter());
    		xstream.processAnnotations(cls);
    		T obj = (T) xstream.fromXML(xmlStr);
    		return obj;
    	}
    
    	/**
    	 * 从xml文件读取报文
    	 * 
    	 * @Title: toBeanFromFile
    	 * @Description: TODO
    	 * @param absPath  绝对路径
    	 * @param fileName 文件名
    	 * @param cls
    	 * @throws Exception
    	 * @return T
    	 */
    	public static <T> T toBeanFromFile(String absPath, String fileName, Class<T> cls) throws Exception {
    		String filePath = absPath + fileName;
    		InputStream ins = null;
    		try {
    			ins = new FileInputStream(new File(filePath));
    		} catch (Exception e) {
    			throw new Exception("读{" + filePath + "}文件失败!", e);
    		}
    
    		return toBeanFromFile(ins, cls);
    	}
    
    	/**
    	 * 从文件流中读取文件
    	 * 
    	 * @param in
    	 * @param cls
    	 * @return
    	 * @throws Exception
    	 */
    	@SuppressWarnings("unchecked")
    	public static <T> T toBeanFromFile(InputStream in, Class<T> cls) throws Exception {
    
    		XStream xstream = new XStream(new DomDriver());
    		xstream.processAnnotations(cls);
    		T obj = null;
    		try {
    			obj = (T) xstream.fromXML(in);
    		} catch (Exception e) {
    			// TODO Auto-generated catch block
    			throw new Exception("文件流读取失败!", e);
    		}
    		if (in != null)
    			in.close();
    		return obj;
    	}
    
    }
    

      

      

      

  • 相关阅读:
    Autodesk Infrastructure Map Server(AIMS)/MapGuide API 培训材料第6章
    安装Vault Professional Server的一些问题
    Autodesk Infrastructure Map Server(AIMS)/MapGuide API 培训材料第2章
    C++的构造函数和析构函数
    一些常用的字符串hash函数
    类的operator new与operator delete的重载
    计算字符串的相似度(编辑距离)
    C++的重载(overload)与重写(override)
    穷举法解24点游戏
    C语言字符串库函数的实现
  • 原文地址:https://www.cnblogs.com/ShaoXin/p/9591493.html
Copyright © 2020-2023  润新知