newbiecihuy newbiecihuy - 5 months ago 14
JSON Question

How to Make Json Format?

How to make JSON for this format

[{"Id":1,"title":"Tester","start":"2016-06-10","point":{"lat":"6.1123231","lon":"106.7796778"},"options":{"theme":"red"}},
{"Id":2,"title":"Tester2","start":"2016-06-10","point":{"lat":"6.4779429","lon":"106.861167"},"options":{"theme":"orange"}}]


using servlet.

This my servlet code

JSONArray arrayObj = new JSONArray();
JSONObject obj = null;
for (int i = 0; i < listData.size(); i++) {
obj = new JSONObject();
EntityTracking dataTracking = listData.get(i);

if (dataTracking.getIdTracking() == null) {
obj.put("Id", "");
} else {
obj.put("Id", dataTracking.getIdTracking());
obj.put("title", dataTracking.getUser_name().getUserName().toUpperCase());
obj.put("start", sdf.format(dataTracking.getTglSend()));
obj.put("point","{");
obj.put("lat", dataTracking.getGetLatitude());
obj.put("lon", dataTracking.getGetLongitude());
obj.put("}","");
obj.put("options","{");
obj.put("theme", dataTracking.getTheme());
obj.put("}","");

arrayObj.add(obj);
}


My outPut JSON format

[{"Id":1,"title":"Tester1","start":"2016-06-10","point":"{","lat":"-6.2206080","lon":"106.7810652","}":"","options":"{","theme":"red"},{"Id":2,"title":"Tester2","start":"2016-06-10","point":"{","lat":"-6.2216851","lon":"106.7822585","}":"","options":"{","theme":"orange"}]


I have tried it many times but I've been unsuccessful. Please help!

Answer

The values of point and options need to be other JSONObject instances.

JSONObject point = new JSONObject();
point.put("lat", dataTracking.getGetLatitude());
point.put("lon", dataTracking.getGetLongitude());
obj.put("point", point);

JSONObject options = new JSONObject();
options.put("theme", dataTracking.getTheme());
obj.put("options", options);

Maybe you should read up on how JSON actually works: Introducing JSON