0

I have a JSONArray emitted by a servlet, like a REST API. I have followed a few links and tried to parse this URL. I am able to receive the URL and print it out from my client servlet, but how do I parse it? So far this is what I have

PrintWriter out = response.getWriter();
        response.setContentType("application/json");
        response.setHeader("Cache-Control", "nocache");
        response.setCharacterEncoding("utf-8");

        String out1 = new Scanner(new URL("http://localhost:8080/myproject/servletone").openStream(), "UTF-8").useDelimiter("\\A").next();
          out.print(out1);

The output is a json array as follows,

[{"name":"abc","age":"80","gender":"male"},{"name":"hello","age":"45","gender":"‌​female"}]

I need to be able to access each of the individual elements name, age, gender in each of the arrays.

IAMTubby
  • 1,627
  • 4
  • 28
  • 40
  • Do you want to parse in java or browser? Try this solution http://stackoverflow.com/questions/2591098/how-to-parse-json-in-java – kamoor Dec 04 '14 at 17:47
  • @kamoor1982, thanks for the reply. But I kind of already know how to parse json in java. My question is more on, how to get the json contents from the URL into a JSONArray format so I can psarse it. – IAMTubby Dec 04 '14 at 20:33

1 Answers1

0

I am assuming out1 has the string you posted in the question. Following code should work then,

JSONArray array = new JSONArray(ou1);
System.out.println(((JSONObject)array.get(0)).get("name"));
kamoor
  • 2,909
  • 2
  • 19
  • 34