Reputation: 643
I have written a jsp code to output the details of mobiles in a list which i want to convert it into jsonarray , i want to know how it is done.
I am getting the json output as
{
1: {
mobile_id: 1,
mobile_name: "HTC-One-X",
mobile_image: "htc-one-x.jpg",
mobile_price: "35,000"
},
2: {
mobile_id: 2,
mobile_name: "Samsung-Galaxy-S5",
mobile_image: "s5.jpg",
mobile_price: "45,000"
}
}
But i want the output to look like this
{
Mobiles:[
{
mobile_id: 1,
mobile_name: "HTC-One-X",
mobile_image: "htc-one-x.jpg",
mobile_price: "35,000"
},
{
}
]
}
My json_mobile.jsp
<%
ServerSql serverSql = new ServerSql();
request.setCharacterEncoding("utf8");
response.setContentType("application/json");
List<String> list = serverSql.getMobile_details();
int recordCounter = 0;
JSONObject jsonObject = new JSONObject();
//JSONArray jArray = jsonObject.optJSONArray("Mobiles");
for (int i = 0; i < list.size(); i++) {
JSONObject formDetailsJson = new JSONObject();
formDetailsJson.put("mobile_id", ++recordCounter);
formDetailsJson.put("mobile_name", list.get(++i));
formDetailsJson.put("mobile_price", list.get(++i));
formDetailsJson.put("mobile_image", list.get(++i));
jsonObject.put(recordCounter, formDetailsJson);
}
out.print(jsonObject.toString());
%>
Can somebody suggest me how to do it ? Thanks
Upvotes: 0
Views: 239
Reputation: 94
Without knowing the language or library I can't test this. But I think your really close to what you want.
I think if you add this to the end of the code...right before the out.print. It will be like you want. Except the numeric index will exists, but was not explicitly shown in your question.
JSONObject jsonObjectFinal = new JSONObject(); jsonObjectFinal.put("Mobiles", jsonObject);
Final output would look like this more than likely:
{
Mobiles:[
0: {
mobile_id: 1,
mobile_name: "HTC-One-X",
mobile_image: "htc-one-x.jpg",
mobile_price: "35,000"
},
1: {
}
]
}
Upvotes: 1