This is my java method:
public String getEvents(String cat, int start, int step) {
//JSONArray list = new JSONArray();
List<String> list = new ArrayList();
if (cat.equalsIgnoreCase("D")){
for (int i=0; i<listDog.size(); i++){
JSONObject obj = new JSONObject();
System.out.println("di=" + i + "=" + (String)listDog.get(i));
obj.put("event_id",new String((String)listDog.get(i)));
list.add(obj.toJSONString());
}
}
else {
for (int i=0; i<listHorse.size(); i++){
JSONObject obj = new JSONObject();
System.out.println("i=" + i + "=" + (String)listHorse.get(i));
obj.put("event_id",new String((String)listHorse.get(i)));
list.add(obj.toJSONString());
}
}
return list.toString();
}
and below is how I convert it to json:
Map map = new HashMap();
Gson gson = new GsonBuilder().disableHtmlEscaping().create()
....
String result = service.getEvents(cat, Integer.parseInt(start), Integer.parseInt(step));
String objs = gson.toJson(result);
map.put("result", objs);
.....
String output = gson.toJson(map);
System.out.println("output->" + output);
out.println(output);
out.flush();
out.close();
I'm getting the below JSON string from the server side:
{
"result": "\"[{\\\"event_id\\\":\\\"2139114\\\"}]\"",
"eventList": "[{\"eventId\":164151,\"meetingCode\":\"5G8QV\",\"meetingName\":\"Kranji\",\"eventTime\":\"13:20:00\",\"eventCode\":\"07:50:00\",\"category\":\"HR\"},{\"eventId\":163890,\"meetingCode\":\"5G8MW\",\"meetingName\":\"Henlow\",\"eventTime\":\"02:30:00\",\"eventCode\":\"21:00:00\",\"category\":\"DG\"}]"
}
and I convert it like this:
success: function(data) {
console.log("SERVLET DATA: " + data.replace("\n", ""));
if (typeof(data) !== 'undefined' && data !== '' && data !== null) {
data = data.replace("\n", "");
var jsonData = JSON.parse(data);
//console.log(jsonData);
for (var i in jsonData) {
var event = jsonData[i];
var event2 = JSON.stringify(jsonData[i]);
var event3 = JSON.parse(event);
console.log("init:" + event.event_id);
}
}
in all three logs, I'm getting "undefined". Please tell me how can I get the "event_id" value from the below json string?
"result": "\"[{\\\"event_id\\\":\\\"2139114\\\"}]\""
I checked validity of json string online and it says no errors found.
is there any issue here or how to access "event_id" field ?
resultandeventList. Both have a string as the value, not an object.resultandeventListas string which also need to be parsed to turn them in to arrays, it can be made a lot more simple than that.