2017-04-25 88 views
0

我得到一個JSON數組作爲響應從其餘webservice,我想遍歷它來獲得它的各種屬性。有多個json數組具有相同的名稱,只有屬性值和不同。爲此,我嘗試了各種代碼片段。我已經提到了所有我嘗試過的代碼片斷,並帶有錯誤信息。getJSONObject(int)是未定義的類型JSONArray

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

web服務的響應有點像

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

回答

0

您不必使用分析器,監守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(); 
    } 
+0

構造函數JSONArray(String)是未定義的錯誤是c oming –

+0

什麼是你使用的lib? json有很多libs –

+0

org.json.simple.JSONArray; –

相關問題