如何在JSP中访问JSONArray元素

时间:2015-01-04 15:04:12

标签: java json jsp arrays

我的JSONArray是

[
   {"id":1,
    "programs_idprograms":3,
    "description":"course description",
    "idCourse":"course title"
   },
   {"id":2,
    "programs_idprograms":3,
    "description":"course description2",
    "idCourse":"course title2"
   }
]  

存储在名为bean2

的字符串中

2 个答案:

答案 0 :(得分:1)

JSONArray array = new JSONArray(bean2);
for(int i=0;i<array.length();i++){
    JSONObject object = array.getJSONObject(i);
    int id = object.getInt("id");
    int programs_idprograms = object.getInt("programs_idprograms");
    String description = object.getString("description");
    String idCourse = object.getString("idCourse");   
}

答案 1 :(得分:1)

试一试:

jsonArray = [ {"id":1,
"programs_idprograms":3,
"description":"course description",
"idCourse":"course title"
},  ... ];

一种方法是在Javascript代码中构造html,如下所示:

 var myHTMLStr = '<table>';
 for(var i in jsonArray) {
 myHTMLStr+='<tr><td>' + jsonArray[i]['id'] + '</td><td>' + jsonArray[i]  ['programs_idprograms'] +   '</td></tr>';

 }
myHTMLStr+='</table>';

现在显示HTML字符串:

document.getElementById('tableOutput').innerHTML = myHTMLStr;