Bean轉XML
阿新 • • 發佈:2018-09-05
clas svc out tid lis als 實體類 esp return
將實體類轉為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 = "\n"; /** * 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; } }
Bean轉XML