对于JSONArray类型,未定义getJSONObject(int)

时间:2017-04-25 07:17:56

标签: arrays json

我从rest webservice获得一个JSON数组,我想迭代它以获得它的各种属性。有多个json数组具有相同的名称,只有属性值和不同。为此,我尝试了各种代码片段。我已经提到了所有我尝试过的代码片段,并提出了错误。

   ResponseEntity<String> response = restTemplate.exchange("xyz.com",
            HttpMethod.GET, entity, String.class);
    JSONParser parser=new JSONParser();
    System.out.println("Response is"+response.getBody());

    try{
        //JSONObject outerObject = (JSONObject)parser.parse(response.getBody()); Class Cast Exception
          //JSONObject jsonObj = new JSONObject(response.getBody()); jsonobject must begin with {
        JSONArray jsonArray = (JSONArray) parser.parse(response.getBody());
        for (int i = 0; i < jsonArray.size(); i++)
        {                 
              /*JSONObject object = jsonArray.getJSONObject(i);*/// getJSONObject(int) is undefined for the type JSONArray

        }
    }catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Webservices响应就像

[
{"mutualFund":{"fundCode":"xyz","fundName":"123","isin":"IE000"}},
{"mutualFund":{"fundCode":"xyz","fundName":"123","isin":"xyz"}},
{"mutualFund":{"fundCode":"xyz","fundName":"123","sedol":"WB1"}}
 ]

1 个答案:

答案 0 :(得分:0)

你不必使用Parser,因为json数组构造函数将字符串作为参数

下载以下JSON lib以使json易于解析

 ResponseEntity<String> response = restTemplate.exchange("xyz.com",
            HttpMethod.GET, entity, String.class);

    System.out.println("Response is"+response.getBody());

    try{
        JSONArray outerObject = new JSONArray(response.getBody());

       for(JSONObject object: outerObject)
{
// Your Logic
}
    }catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }