narahari_arjun
narahari_arjun

Reputation: 643

how to add a list of string into json object in jsp?

I have written a program in jsp to insert values into database , now i want to retrieve those values from database and show it in json format. I have name , gender and age parameters and i am getting it in a list and i want to show it as Users{ 1:{name:abc,gender:male,age:21},2:{name:xyz,gender:female,age:25},...... }

My Jsp code

<%
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());
%>

I am getting output as :

{"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"}]}

I am new to json , so need some guidance Thank You

Upvotes: 3

Views: 3283

Answers (1)

Rajeev
Rajeev

Reputation: 1840

'Writing java code on jsp is a bad practice'. Though you can write. As I can see you list contains all details in string format and every 3rd index interval there is a new record details to do so you can write like.

   <%
 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());
%>

Above code will output like you mentioned in your question. Make sure that your list contains records multiple of 3 otherwise you may get IndexOutOfBound exception.

Upvotes: 2

Related Questions