我已经用jsp编写了一个将值插入数据库的程序,现在我想从数据库中检索这些值并以json格式显示。我有名称,性别和年龄参数,我将其显示在列表中,我想将其显示为Users {1:{name:abc,gender:male,age:21},2:{name:xyz,gender:女,年龄:25},......}
我的Jsp代码
<% PrintWriter outt = response.getWriter(); JSONObject obj = new JSONObject(); Insert_UserDetails details = new Insert_UserDetails(); request.setCharacterEncoding("utf8"); response.setContentType("application/json"); List<String> list = details.getAllUsers(); JSONArray jArray = new JSONArray(); for (int i = 0; i < list.size(); i++) { JSONObject formDetailsJson = new JSONObject(); formDetailsJson.put("result", list.get(i)); jArray.add(formDetailsJson); } obj.put("form_details", jArray); out.print(obj.toString()); %>
我得到的输出为:
{"form_details":[{"result":"arjun"},{"result":"male"},{"result":"21"}, {"result":"ravi"},{"result":"male"},{"result":"30"},{"result":"pushpa"}, {"result":"female"},{"result":"57"},{"result":"usha"},{"result":"female"}, {"result":"60"},{"result":"bharat"},{"result":"male"},{"result":"30"}, {"result":"ramesh"},{"result":"male"},{"result":"29"},{"result":"ramesh"}, {"result":"male"},{"result":"29"}]}
我是json的新手,所以需要一些指导谢谢
“在jsp上编写Java代码是一种不好的做法”。虽然可以写。如我所见,列表包含字符串格式的所有详细信息,每个第3个索引间隔都有一个新的记录详细信息,您可以这样编写。
<% PrintWriter outt = response.getWriter(); JSONObject obj = new JSONObject(); JSONObject finalJSON = new JSONObject(); Insert_UserDetails details = new Insert_UserDetails(); request.setCharacterEncoding("utf8"); response.setContentType("application/json"); List<String> list = details.getAllUsers(); int recordCounter=1; JSONArray jArray = new JSONArray(); for (int i = 0; i < list.size(); i++) { JSONObject formDetailsJson = new JSONObject(); formDetailsJson.put("name", list.get(i)); formDetailsJson.put("gender", list.get(++i)); formDetailsJson.put("age", list.get(++i)); finalJSON.put(recordCounter,formDetailsJson); recordCounter++; } out.print(finalJSON.toString()); %>
上面的代码将像您在问题中提到的那样输出。确保您的列表包含3条记录的倍数,否则可能会出现IndexOutOfBound异常。
IndexOutOfBound