简体   繁体   中英

How to convert a JSONObject to a object contains java.util.Set field

There is a model class:

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 + "]";
    }
}

And I execute the function below:

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

}

It cannot convert jsonObject to Book object, and there will be a exception. How can I convert jsonObject to Book object successful?

尝试Gson

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM