20190408 XStream解析List
XStream解析List
使用的JavaBean
- 普通JavaBean
public class Book {
private String name;
public Book() {
}
public Book(String name) {
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
- 包含List的JavaBean
public class BookBag {
private int price;
private String name;
private Date date;
private List<Book> books;
public int getPrice() {
return price;
}
public void setPrice(int price) {
this.price = price;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public List<Book> getBooks() {
return books;
}
public void setBooks(List<Book> books) {
this.books = books;
}
}
开始测试
1. 初始版
@Test
public void test1() {
BookBag bookBag = new BookBag();
bookBag.setPrice(100);
bookBag.setName("张三");
bookBag.setDate(new Date());
Book book1 = new Book("西游记");
Book book2 = new Book("红楼梦");
ArrayList<Book> books = new ArrayList<>();
books.add(book1);
books.add(book2);
bookBag.setBooks(books);
XStream xStream = new XStream();
String s = xStream.toXML(bookBag);
System.out.println(s);
}
结果:
<test.hwj.bean.BookBag>
<price>100</price>
<name>张三</name>
<date>2019-04-08 07:38:18.854 UTC</date>
<books>
<test.hwj.bean.Book>
<name>西游记</name>
</test.hwj.bean.Book>
<test.hwj.bean.Book>
<name>红楼梦</name>
</test.hwj.bean.Book>
</books>
</test.hwj.bean.BookBag>
2. 为JavaBean加上注释,@XStreamAlias
修改代码:
@XStreamAlias("BookBag")
public class BookBag {
@XStreamAlias("Book")
public class Book {
// 开启注释
xStream.autodetectAnnotations(true);
结果:
<BookBag>
<price>100</price>
<name>张三</name>
<date>2019-04-08 07:45:41.187 UTC</date>
<books>
<Book>
<name>西游记</name>
</Book>
<Book>
<name>红楼梦</name>
</Book>
</books>
</BookBag>
3. 消除List外的大标签
修改代码:
@XStreamImplicit
private List<Book> books;
结果:
<BookBag>
<price>100</price>
<name>张三</name>
<date>2019-04-08 07:47:47.432 UTC</date>
<Book>
<name>西游记</name>
</Book>
<Book>
<name>红楼梦</name>
</Book>
</BookBag>
4. 对Date进行处理
修改代码:
// 注册转换器
xStream.registerConverter(new DateConverter("yyyy-MM-dd HH:mm:ss", null));
结果:
<BookBag>
<price>100</price>
<name>张三</name>
<date>2019-04-08 07:51:30</date>
<Book>
<name>西游记</name>
</Book>
<Book>
<name>红楼梦</name>
</Book>
</BookBag>