3

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

1 Answer 1

2

'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.

Sign up to request clarification or add additional context in comments.

1 Comment

thank you sir , first it gave me indexoutofbound exception , due to list.get(i) , but then i did list.get(++i) and it worked

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.