如何将JSONObject转换为对象包含java.util.Set字段

时间:2013-08-01 10:07:39

标签: java json

有一个模型类:

public class Book {
    private String id;
    private Set<String> authors = new HashSet<String>();  //Set field

    public String getId() {
        return id;
    }
    public void setId(String id) {
        this.id = id;
    }
    public Set<String> getAuthors() {
        return authors;
    }
    public void setAuthors(Set<String> authors) {
        this.authors = authors;
    }
    @Override
    public String toString() {
        return "Book [authors=" + authors + ", id=" + id + "]";
    }
}

我执行以下功能:

public void test3() {
    Book book = new Book();
    book.setId("T2");
    Set<String> authors = new HashSet<String>();
    authors.add("Tom");
    authors.add("King");
    book.setAuthors(authors );

    JSONObject jsonObject = JSONObject.fromObject(book);
    System.out.println(jsonObject);

    Book b = (Book) JSONObject.toBean(jsonObject, Book.class);
    System.out.println(b.toString());

}

它无法将jsonObject转换为Book对象,并且会出现异常。 如何将jsonObject转换为Book对象成功?

1 个答案:

答案 0 :(得分:1)

尝试Gson

Book b = new Gson().fromJson(jsonObject, Book.class);