在將JSON格式的數(shù)據(jù)轉(zhuǎn)換為BEAN的JAVA數(shù)據(jù)格式時,需要提供帶參數(shù)和不帶參數(shù)的構(gòu)造函數(shù),如果僅僅提供了帶參數(shù)的構(gòu)造函數(shù),而沒有提供不帶參數(shù)的構(gòu)造函數(shù),會發(fā)生如下的異常:
Exception in thread "main" net.sf.json.JSONException: java.lang.InstantiationException:
這表明BEAN沒有正常的被初始化:

public static void json2bean()
{
JSONObject jo = JSONObject
.fromObject("{bookname:\"C++程序設計\",isbn:\"885596-989\",author:\"小東\"}");
Book book = (Book) JSONObject.toBean(jo, Book.class);
System.out.println(book.getAuthor() + "-" + book.getBookname());

}
所以在Book.java文件中,除了要提供帶參數(shù)的構(gòu)造函數(shù)

public Book(String bookname, String isbn, String author)
{
this.bookname = bookname;
this.isbn = isbn;
this.author = author;
}
外,還要提供不帶參數(shù)的構(gòu)造函數(shù):

public Book()
{
System.out.println("this is run
");
}
這樣就不會報那個異常了.為了表明不帶參數(shù)的構(gòu)造函數(shù)被調(diào)用,可以在函數(shù)中加入一條輸出語句,以表明不帶參數(shù)的構(gòu)造函數(shù)是否被調(diào)用.
posted on 2008-10-31 09:51
henry1451 閱讀(616)
評論(0) 編輯 收藏