XML和实体类之间的转换

Posted java学习中转站

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了XML和实体类之间的转换相关的知识,希望对你有一定的参考价值。

言简意赅:

1.jar包的maven 坐标

<dependency> <groupId>com.thoughtworks.xstream</groupId> <artifactId>xstream</artifactId> <version>1.4.10</version> </dependency>

2.进行创建实体类(要转换为xml格式)

package cn.abchinalife.pos.ploicyQueryFirstPage.dao.req;import com.thoughtworks.xstream.annotations.XStreamAlias;@XStreamAlias("ABCXQAPPEDOR")public class PloicyListRootReq  { @XStreamAlias("Header")    private Header header; @XStreamAlias("Body")    private PloicyListBodyReq ploicyListBodyReq; @Override public String toString() { return "PloicyListRootReq{" + "header=" + header + ", ploicyListBodyReq=" + ploicyListBodyReq + '}'; }
public Header getHeader() { return header;    } public void setHeader(Header header) { this.header = header;    } public PloicyListBodyReq getPloicyListBodyReq() { return ploicyListBodyReq;    } public void setPloicyListBodyReq(PloicyListBodyReq ploicyListBodyReq) { this.ploicyListBodyReq = ploicyListBodyReq;    } public PloicyListRootReq() { }}

哈哈还是换个简单的吧上边的那个没啥用

package cn.abchinalife.pos.ploicyQueryFirstPage.controller.JsonUtil;import com.thoughtworks.xstream.annotations.XStreamAlias;@XStreamAlias("Body")public class A { @XStreamAlias("B") private String b; @XStreamAlias("C") private String c; 自己写get/set/toString/空构造器方法}

package cn.abchinalife.pos.ploicyQueryFirstPage.controller.JsonUtil;import com.thoughtworks.xstream.annotations.XStreamAlias;public class B { @XStreamAlias("D") private String c; @XStreamAlias("E") private String d; 自己写get/set/toString/空构造器方法}

package cn.abchinalife.pos.ploicyQueryFirstPage.controller.JsonUtil;import com.thoughtworks.xstream.annotations.XStreamAlias;@XStreamAlias("C")public class C { @XStreamAlias("A") private A a; @XStreamAlias("B") private B b;    自己写get/set/toString/空构造器方法}

3.业务层

package cn.abchinalife.pos.ploicyQueryFirstPage.controller.JsonUtil;import cn.abchinalife.pos.common.utils.PosCommonUtils;import com.thoughtworks.xstream.XStream;import com.thoughtworks.xstream.io.naming.NoNameCoder;import com.thoughtworks.xstream.io.xml.DomDriver;public class AAA {    public static void main(String[] args) { A a = new A(); a.setB("bbbb");        a.setC("cccc"); B b = new B(); b.setC("cccc2");        b.setD("ddddd"); C c = new C(); c.setA(a);        c.setB(b); //创建xml对象 XStream xstream = new XStream(new DomDriver("UTF-8", new NoNameCoder())); xstream.autodetectAnnotations(true); //转换xml String xml = xstream.toXML(c); xml = PosCommonUtils.addHeader2XML(xml);        System.out.println(xml); }}运行结果:
<?xml version="1.0" encoding="UTF-8"?><C> <A> <B>bbbb</B> <C>cccc</C> </A> <A> <C>cccc2</C> <D>ddddd</D> </A></C>

是不是再找工具类PosCommonUtils哈哈

package cn.abchinalife.pos.common.utils;
import com.thoughtworks.xstream.XStream;import com.thoughtworks.xstream.io.naming.NoNameCoder;import com.thoughtworks.xstream.io.xml.DomDriver;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.http.HttpEntity;import org.springframework.http.HttpHeaders;import org.springframework.http.MediaType;import org.springframework.web.client.RestTemplate;
import java.lang.reflect.Field;import java.text.ParseException;import java.text.SimpleDateFormat;import java.util.Date;import java.util.Random;/** * @author smallKaiGe666 * @date 2020-08-20 15:24 */public class PosCommonUtils {    private static final Logger log = LoggerFactory.getLogger(PosCommonUtils.class); public static final String SIMPLE_FORMAT = "yyyyMMdd"; public static final String SIMPLE_FORMAT_LINE = "yyyy-MM-dd"; public static final String DETAIL_FORMAT = "yyyy年MM月dd日 HH:mm:ss"; public static final String DETAIL_FORMAT_NO_UNIT = "yyyyMMddhhmmss"; public static final String DETAIL_FORMAT_LINE = "HH:mm:ss"; public static final String SIMPLE_FORMAT_Date_Time = "yyyy-MM-dd HH:mm:ss"; public static final String SIMPLE_FORMAT_Date_Time_MSEL = "yyyy-MM-dd HH:mm:ss:SSS"; public static final String SIMPLE_FORMAT_Year_Date = "yyyyMM"; public static final String SIMPLE_FORMAT_Year = "yyyy"; public static final String SIMPLE_FORMAT_Month = "MM";    public static final String SIMPLE_FORMAT_Day = "dd"; /** * 获取20位随机数-----作为交易流水号 serialNo * @return */ public static String getSerialNo(){ String msg = ""; String res = ""; Date date = new Date(); Random ran = new Random(); SimpleDateFormat sdf = new SimpleDateFormat("YYYYMMddHHmmssSSS"); msg = sdf.format(date); for (int i = 0; i < 3; i++) { res += ran.nextInt(10); }        return msg+res;    } /** * 返回当前时间按照HH:mm:ss格式 * @return */ public static String getTime(){ SimpleDateFormat df = new SimpleDateFormat("hh:mm:ss"); Date date = new Date();        String format = df.format(date);       return format; }
/** * @Description:为xml字符串添加报文头信息 * <?xml version="1.0" encoding="GBK"?> * @author li_bin * @Date: 2018年3月28日 * @throws * @param xml * @return */ public static String addHeader2XML(String xml) {// String head = "<?xml version=\"1.0\" encoding=\"GBK\"?>"; String head = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"; xml = (xml == null || "".equals(xml) || xml.startsWith(head)) ? xml : head + System.getProperty("line.separator") + xml; return xml; }

/** * @Description:将String 封装进HttpEntity中,并将HttpEntity的编码设置为UTF-8 * 本方法是为了解决restTemplate 默认编码为ISO8859-1的问题 * @author li_bin * @Date: 2018年3月28日 * @throws * @param xml * @return */ public static HttpEntity<String> str2HttpEntity(String xml) { HttpHeaders headers = new HttpHeaders(); MediaType type = MediaType.parseMediaType("application/json; charset=UTF-8"); headers.setContentType(type); headers.add("Accept", MediaType.APPLICATION_JSON.toString()); HttpEntity<String> formEntity = new HttpEntity<String>(xml, headers); return formEntity;    }    public static String str2HttpEntity(String xml, String url) {        HttpHeaders headers = new HttpHeaders();        RestTemplate restTemplate = RestTemplateUtil.getChineseRestTemplate(); //设置请求格式 headers.setContentType(MediaType.APPLICATION_JSON_UTF8); //设置响应格式        headers.add(HttpHeaders.ACCEPT, MediaType.APPLICATION_XML_VALUE);        return restTemplate.postForObject(url, xml, String.class);    } /** * 返回当前字符串型日期 * * @return String 返回的字符串型日期 */ public static Date getCurDate() { // Calendar calendar = Calendar.getInstance(); // SimpleDateFormat simpledateformat = new // SimpleDateFormat("yyyy-MM-dd"); // String strDate = simpledateformat.format(calendar.getTime()); return new Date(); }
/** * 返回当前日期时间字符串<br> * 默认格式:yyyy-mm-dd hh:mm:ss * * @return String 返回当前字符串型日期时间 */ public static String getCurTime() { String returnStr = null; SimpleDateFormat f = new SimpleDateFormat("HH:mm:ss"); Date date = new Date(); returnStr = f.format(date); return returnStr; }
/*** * 字符串转为日期格式 * * @param stringDate * @return */ public static Date getDateForString(String stringDate) { SimpleDateFormat sdf = new SimpleDateFormat( "yyyy-MM-dd" ); Date date = null; try { date = sdf.parse(stringDate); } catch (ParseException e) { log.error(e.getMessage(),e); } return date; }
/** * 根据传入日期,返回yyyyMMdd格式字符串 * * @param date * @return * @author wux * @since 2018年5月9日 下午8:05:11 */ public static String getSimpleDate(Date date) { SimpleDateFormat myFormat = new SimpleDateFormat(SIMPLE_FORMAT); return myFormat.format(date);    } /*** * 格式化日期 * * @param myDate * @param fromatString * @return */ public static String formatDate(Date myDate, String fromatString) { SimpleDateFormat myFormat = new SimpleDateFormat(fromatString); return myFormat.format(myDate); }
/** * 将传入xml文本转换成Java对象 * @Title: toBean * @Description: TODO * @param xmlStr * @param cls xml对应的class类 * @return T xml对应的class类的实例对象 * * 调用的方法实例:PersonBean person=XmlUtil.toBean(xmlStr, PersonBean.class); */ public static <T> T toBean(String xmlStr,Class<T> cls){ XStream xstream = new XStream(new DomDriver("UTF-8", new NoNameCoder())); xstream.processAnnotations(cls); //通过注解方式的,一定要有这句话 Object fromXML = xstream.fromXML(xmlStr); return (T)fromXML ;    }}

上边就是 最为简单的将实体类转换为xml但是需要你在每个类上边进行配置注解

 @XStreamAlias("C")

其中括号内的内容就是xml的标签的名字

注意的是 关于集合这里需要注意,有时候需要在类上加 上述标签并不仅仅是在属性中进行添加。


上边是将实体类转换为xml,下边将xml转换为实体类


package cn.abchinalife.pos.ploicyQueryFirstPage.controller.JsonUtil;import cn.abchinalife.pos.common.utils.PosCommonUtils;import com.thoughtworks.xstream.XStream;import com.thoughtworks.xstream.io.naming.NoNameCoder;import com.thoughtworks.xstream.io.xml.DomDriver;/** * @author zhangkaipeng * @date 2020-09-27 12:32 */public class AAA {    public static void main(String[] args) { A a = new A(); a.setB("bbbb"); a.setC("cccc");
B b = new B(); b.setC("cccc2"); b.setD("ddddd");
C c = new C(); c.setA(a);        c.setB(b); //创建xml对象 XStream xstream = new XStream(new DomDriver("UTF-8", new NoNameCoder())); xstream.autodetectAnnotations(true); //转换xml String xml = xstream.toXML(c); xml = PosCommonUtils.addHeader2XML(xml);        System.out.println(xml);        String xml2 =xml; C c2 = new C();        c2 = PosCommonUtils.toBean(xml2, C.class);        System.out.println("转换的c2为"+c2.toString()); }}

是不是还在找工具类还是上边的那个实体类。

好了我工作中用到的就是这个,有什么问题随时 来找我。

以上是关于XML和实体类之间的转换的主要内容,如果未能解决你的问题,请参考以下文章

XML和实体类之间的转换

C# XML和实体类之间相互转换(序列化和反序列化)

JAVA中,类、对象、实体、实体类、实体对象之间存在怎样的联系??请高手做形象的解释。

简单实体类和xml文件的相互转换

把实体类转成xml让list的最外层标签失效

C#实体类与XML相互转换