開始看網上關於json的例子程序段,實驗了一把發現結果和網上例子程序的結果不一致,後來發現使用json需要導入的jar包不全,只導入json-lib-2.2.2-jdk15.jar ,還需以下幾個包:commons-beanutils-1.7.0.jar
commons-collections-3.2.jar
commons-lang.jar
commons-logging-1.1.jar
ezmorph-1.0.4.jar
這時在測試得到了想要的結果
Question q2 = new Question();
q2.setId(2);
q2.setDescription("descrsssss");
q2.setPointInfo("pointkkkk");
q2.setType(3);
Question q1 = new Question();
q1.setId(1);
q1.setDescription("descrsssss");
q1.setPointInfo("pointkkkk");
q1.setType(3);
JSONObject jsonObject = new JSONObject().fromObject(q2);
System.out.println(jsonObject);
List list = new ArrayList();
list.add(q1);
list.add(q2);
JSONArray jsonArr= JSONArray.fromObject(list);
System.out.println(jsonArr);
輸出:{"description":"descrsssss","id":2,"pointInfo":"pointkkkk","type":3}[{"description":"descrsssss","id":1,"pointInfo":"pointkkkk","type":3},{"description":"descrsssss","id":2,"pointInfo":"pointkkkk","type":3}]
頁面
$.post("showQuestions?type="+type,null,callbackShowQuestions,"json");
這時在回調函數的參數data獲得的就是json轉換後的js對象數組,
以下標方式便可訪問數組裏的相應對象信息。