如何在jsp中将字符串列表添加到json对象中?

时间:2015-03-11 18:42:39

标签: json jsp

我已经在jsp中编写了一个程序来将值插入到数据库中,现在我想从数据库中检索这些值并以json格式显示它。 我有名字,性别和年龄参数,我在列表中得到它,我想把它显示为     用户{     1:{名称:ABC,性别:雄性,年龄:21},2:{名称:XYZ,性别:女,年龄: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的新手,所以需要一些指导 谢谢

1 个答案:

答案 0 :(得分:2)

&#39;在jsp上编写java代码是一种不好的做法&#39;。虽然你可以写。我可以看到你的列表包含字符串格式的所有细节,每隔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异常。