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