如何访问 JSP 中的 JSONArray 元素

How can I access JSONArray elements in JSP

我的 JSONArray 是

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

存储在一个名为bean2的字符串中

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");   
}

试一试:

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;