0
有一个模型类:如何一个JSONObject转换为对象包含java.util.Set中的场
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到书对象,并会有一个例外。 如何将jsonObject转换为Book对象成功?
什么是例外?你的json是什么样的。 –
异常是:net.sf.json.JSONException:在设置属性=作者类型接口java.util.List时出错 \t at net.sf.json.JSONObject.toBean(JSONObject.java:468) \t at net。 sf.json.JSONObject.toBean(JSONObject.java:242) \t at com.augmentum.ot.Test.test3(Test.java:54) \t at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)... –
尝试使用[GSon](http://www.json.org/)进行转换 – swapy