2

i am getting json array in the output.i want to access the specific key elments from the response .how can i ..?

 ResponseEntity <String> respone;
      try {
          response =
      restTemplate.exchange(url, HttpMethod.POST, requestEntity, String.class);



      String response=response.getBody(); 
      JSONObject res = new JSONObject();
      res.put("result", response);
      System.out.println(res);
      int len=res.size();
      System.out.println(len);
      JSONParser parser=new JSONParser();
        Object obj = parser.parse(response);
        JSONArray array = (JSONArray)obj;
        System.out.println(array.get(0)); } 

this is respponse format i m getting in output.i want to access the bid from the response.how can i?

  [
      {
            "bName": "abc", 
            "bId": "n86nbnhbnghgy76"

          }
        ]
user3189357
  • 153
  • 1
  • 6
  • 16
  • 1
    jackson? gson? libraries that help you parse pretty easily through elements – Andrei Sfat Sep 29 '14 at 08:05
  • @sfat ... i am using jackson.. – user3189357 Sep 29 '14 at 08:08
  • you're using JSONParser. If you have jackson in your project, just do a ObjectMapper mapper = new ObjectMapper(); AClassThatMatchesTheModelOfThatJson thatModel = mapper.readValue(response, AClassThatMatchesTheModelOfThatJson.class); – Andrei Sfat Sep 29 '14 at 08:12
  • 1
    possible duplicate of [Accessing members of items in a JSONArray with Java](http://stackoverflow.com/questions/1568762/accessing-members-of-items-in-a-jsonarray-with-java) – Muhammed Refaat Sep 29 '14 at 08:12

2 Answers2

2

Decode your string using JSONArray(String json) constructor:

String response = response.getBody(); 
JSONArray res = new JSONArray(response);
String bId = res.getJSONObject(0).get("bId");
System.out.println(bid);
Nicolas Albert
  • 2,586
  • 1
  • 16
  • 16
0

EDIT

Try following:

  String response=response.getBody(); 
  JSONObject res = new JSONObject();
  System.out.println(res);
  int len=res.size();
  System.out.println(len);
  JSONParser parser=new JSONParser();
    Object obj = parser.parse(response);
    JSONArray array = (JSONArray)obj;
    res=(JSONObject)array.get(0);
    System.out.println(res.get("bId"));

Output :

n86nbnhbnghgy76

This one is based on your code and with Simple Json Library.

Darshan Lila
  • 5,772
  • 2
  • 24
  • 34