javascript
创建JSON集合使用JSONArray.fromObject 转化后得到的jsonArray集为空?
個人經歷教訓,答案在末尾最
近況說明:最近在寫一個論壇系統的后臺,其中涉及到文章類(article)與評論類(article_comment)的關系,我在article類中創建了一個獲取文章評論的function【該方法獲取文章所有評論,組成JsonArray集合后再轉化為String格式返回】:
public String getArticalComments() {//獲取文章評論集合List<artical_comment> article_comments= new ArrayList<article_comment>(); try { ResultSet res = DoSQL.executeQuery("SELECT *FROM article_comment WHERE artical_id = " + this.article_id);//通過文章id尋找評論while (res.next()) {System.out.println("獲取評論id:"+res.getInt("id"));artical_comment A = new artical_comment(res.getInt("id"));//通過文章id尋找到評論id,并創建評論類//System.out.println(A.toString());artical_comments.add(A);//將評論添加到對象數組}System.out.println(article_comments);} catch (SQLException e) {// TODO 自動生成的 catch 塊System.out.println("獲取res查詢結果集失敗");e.printStackTrace();}//創建JSON集合JSONArray jsonarray = JSONArray.fromObject(artical_comments);System.out.println("轉換jsonarray后:"+jsonarray);//把JSON集合轉出String字符串輸出String str = jsonarray.toString();System.out.println("轉換str后:"+str);return str;//str代表轉化成String格式后的某文章評論集合}起初發現控制臺打印出來的str為{} 即 空,通過調試發現,JSONArray jsonarray = JSONArray.fromObject(article_comments);這一步得到的jsonarray也為空,但是List<article_comment> article_comments= new ArrayList<article_comment>();artical_comments這個集合的內容不為空。
這就說明,問題發生在JSONArray jsonarray = JSONArray.fromObject(article_comments);這一行代碼上面了,也就是list對象集合轉json格式造成異常,一番搜索,得出結果【劃重點】:
答案:
SONArray.fromObject(object)在對Object轉換的時候是按照domain類中的所有getXXX()方法進行轉換的。如果你在類中寫了非屬性的getXXX()方法,那么返回給你的就會有XXX屬性了,如果在object中沒有寫get方法,那么轉化為jsonArray的時候是獲取不到值的。
總結
以上是生活随笔為你收集整理的创建JSON集合使用JSONArray.fromObject 转化后得到的jsonArray集为空?的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: sql server2005索引
- 下一篇: 你可能从未听过的 Linux 发行版