1

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 ?

7
  • The JSON object has two elements: result and eventList. Both have a string as the value, not an object. Commented Mar 2, 2015 at 10:11
  • 2
    What code is generating that JSON? I would suggest you look at refactoring that to give you a better output. Currently it's giving you result and eventList as string which also need to be parsed to turn them in to arrays, it can be made a lot more simple than that. Commented Mar 2, 2015 at 10:12
  • @RoryMcCrossan I'm using Java and used gson.toJson() to generate the above output and it has no issues when I checked it with online json validator. Commented Mar 2, 2015 at 10:13
  • @LutzHorn yes please tell me how to get "event_id" field from the "result": "\"[{\\\"event_id\\\":\\\"2139114\\\"}]\"" string Commented Mar 2, 2015 at 10:13
  • 5
    It's valid JSON, but you should be returning the values as actual arrays, not serialised strings. Commented Mar 2, 2015 at 10:14

2 Answers 2

1

Firstly, you need to re-factor the getEvents method to return only plain objects (e.g. List), then, put the result in to the target map before passing it to the toJSON method

public class Event {
    String event_id;

    Event(String event_id) {
        this.event_id = event_id;
    }
}

public List<Event> getEvents(String cat, int start, int step)  {

    List<Event> list = new ArrayList<Event>();

    if (cat.equalsIgnoreCase("D")){
        for (int i=0; i<listDog.size(); i++){
            System.out.println("di=" + i + "=" + (String)listDog.get(i));

            list.add( new Event( (String)listDog.get(i) ));
        }
    }
    else {
        for (int i=0; i<listHorse.size(); i++){
            System.out.println("i=" + i + "=" + (String)listHorse.get(i));

            list.add( new Event( (String)listHorse.get(i) ));
        }
    }

    return list;

}

Then, convert your result like this:

Map map = new HashMap();
Gson gson = new GsonBuilder().disableHtmlEscaping().create()

....

List<Event> result = service.getEvents(cat, Integer.parseInt(start), Integer.parseInt(step));

map.put("result", result);

String objs = gson.toJson(map);
Sign up to request clarification or add additional context in comments.

1 Comment

great, I got your idea and changed my logic abit. it really works. Thanks !
0

I changed my java method as below:

public List < UKDashboardEventDTO > getEvents(String cat, int start, int step) {

  //JSONArray list = new JSONArray();
  List < UKDashboardEventDTO > list = new ArrayList();
  UKDashboardEventDTO dto;
  if (cat.equalsIgnoreCase("D")) {
    for (int i = start - 1; i < listDog.size(); i = i + step) {
      //JSONObject obj = new JSONObject();
      dto = new UKDashboardEventDTO();
      System.out.println("di=" + i + "=" + (String) listDog.get(i));
      dto.setEventId(Long.parseLong(listDog.get(i).toString()));
      list.add(dto);
    }
  } else if (cat.equalsIgnoreCase("H")) {
    for (int i = start - 1; i < listHorse.size(); i = i + step) {
      dto = new UKDashboardEventDTO();
      System.out.println("di=" + i + "=" + (String) listHorse.get(i));
      dto.setEventId(Long.parseLong(listHorse.get(i).toString()));
      list.add(dto);
    }
  } else if (cat.equalsIgnoreCase("A")) {
    for (int i = start - 1; i < listAll.size(); i = i + step) {
      dto = new UKDashboardEventDTO();
      System.out.println("di=" + i + "=" + (String) listAll.get(i));
      dto.setEventId(Long.parseLong(listAll.get(i).toString()));
      list.add(dto);
    }
  }

  return list;

}

and used the dto class as below:

public class UKDashboardEventDTO implements Serializable{

    private Long eventId;
  
  ............
  
 }

and pass the values like this:

List < UKDashboardEventDTO > result = service.getEvents(cat, Integer.parseInt(start), Integer.parseInt(step));
map.put("result", result);
//out.println(objs);   

.......


try {
  String objs = gson.toJson(map);
  System.out.println("objs->" + objs);
  out.println(objs);
  out.flush();
  out.close();
} catch (Exception ex) {

}

did not want to do any change to the client side logic. this works !

Comments

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.