json有Fastjson,XML我有XStream

# 一、 前言 通信时,json和java object互转用什么? 对于json,咱有fastjson [https://github.com/alibaba/fastjson](https://github.com/alibaba/fastjson) 虽然有些bug,但在不断完善中。 今天的议题是: 但是因为咱常接一些老系统的WebService,所以会用到XML和java object互转。 以前我都是自己用反射来写一个简单的一级解析。后来发现不够用的了。 于是换更好的库吧。XStream 主页传送门: [http://x-stream.github.io/](http://x-stream.github.io/) 下载jar库当然有多种形式,我习惯了去mvnrepository.com去搜索。多年来的老习惯了。 地址: [https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream](https://mvnrepository.com/artifact/com.thoughtworks.xstream/xstream) 官网给的例子就这么简单: ``` XStream xstream = new XStream(); String xml = xstream.toXML(myObject); // serialize to XML Object myObject2 = xstream.fromXML(xml); // deserialize from XML ``` 然而做出来的效果令人发指,是类似这样: ``` zhangsan 2 2019-12-03 11:30:44.703 UTC 1 g1 2 g2 ``` 可见,它直接把包名加类名去转化了,那么怎么改呢? # 2. 类混叠 和 字段混叠 ## 1) 类混叠 ``` // 类混叠 xstream.alias("User", User.class); xstream.alias("Group", Group.class); ``` 这下好多了 ``` zhangsan 2 2019-12-05 03:27:42.700 UTC 1 g1 2 g2 ``` ## 2) 字段混叠 当然还有字段混叠: ``` // 字段混叠 xstream.aliasField("userName", User.class, "name"); xstream.aliasField("groupName", Group.class, "name"); ``` 结果如下: ``` zhangsan 2 2019-12-05 03:27:42.700 UTC 1 g1 2 g2 ``` ## 3) 注解处理混叠 更优雅 ``` @XStreamAlias("person") // 类混叠 public class User { @XStreamAlias("username") // 字段混叠 @XStreamAsAttribute // 字段作为属性 private String name; @XStreamAlias("年龄") // 字段混叠 private int age; @XStreamOmitField // 忽略字段 private Date birthDay; @XStreamImplicit // 隐式集合混叠 private List groups; public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } public Date getBirthDay() { return birthDay; } public void setBirthDay(Date birthDay) { this.birthDay = birthDay; } public User(String name, int age, Date birthDay) { super(); this.name = name; this.age = age; this.birthDay = birthDay; } public List getGroups() { return groups; } public void setGroups(List groups) { this.groups = groups; } @Override public String toString() { return "User [name=" + name + ", age=" + age + ", birthDay=" + birthDay + ", groups=" + groups + "]"; } } ``` 参考文献: [XStream处理XML用法](https://www.cnblogs.com/qlqwjy/p/11978608.html)

你可能感兴趣的:(json有Fastjson,XML我有XStream)