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);

    }

結果:java

<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);

結果:this

<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外的大標籤

修改代碼:code

@XStreamImplicit
private List<Book> books;

結果:ci

<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進行處理

修改代碼:get

// 註冊轉換器
xStream.registerConverter(new DateConverter("yyyy-MM-dd HH:mm:ss", null));

結果:it

<BookBag>
  <price>100</price>
  <name>張三</name>
  <date>2019-04-08 07:51:30</date>
  <Book>
    <name>西遊記</name>
  </Book>
  <Book>
    <name>紅樓夢</name>
  </Book>
</BookBag>
相關文章
相關標籤/搜索