简体   繁体   中英

how to access json array element in java

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 im getting in output.i want to access the bid from the response.how can i?

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

          }
        ]

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);

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM