2013-07-26 76 views
1

我正在使用Java解析來自服務器的JSON響應。我的最終目標是將結果中的數據放入數組中。目前我使用這個嘗試並獲得結果:將JSON服務器響應解析到JSON數組中

org.json.JSONException: Value blah at 0 of type java.lang.String cannot be converted to JSONObject 

這是我的服務器的:因爲它正在尋找對象的數組,而不是字符串數組

JSONArray jArray = myResponse.getJSONArray("results"); 

此代碼失敗JSON響應:

{ 
    status: "OK", 
    results: [ 
    "blah", 
    "bleh", 
    "blah" 
    ] 
} 

有一個簡單的方法來獲取「結果」值到一個數組?或者我應該只寫我自己的解析器。

感謝

---------- ---------- UPDATE

看起來像我的問題實際上是存在的其他地方,而不是在JSON屬性「結果」正被轉換成JSONArray。

對不起,謝謝你的答案,他們幫助我意識到我正在尋找錯誤的地方。

回答

5

這應該是它。所以你可能試圖在結果中得到JSONObject而不是String。

JSONObject responseObject = new JSONObject(responseString); 
JSONArray resultsArray = responseObject.getJSONArray("results"); 
for (int i=0; i<resultsArray.length(); i++) 
    String resultString = resultsArray.getString(i); 
0

正如你將可能有更多的屬性,只比String[] result,我建議定義一個DTO這樣的:

public class Dto { 
    //of course you should have private fields and public setters/getters, but this is only a sample 
    public String status; 
    public List<String> results;//this can be also an array 
} 

然後在你的代碼:

ObjectMapper mapper = new ObjectMapper(); 
Dto dto = mapper.readValue(inputDtoJson, Dto.class);//now in dto you have all the properties you need