2017-01-22 95 views
-1

我正在Android中創建一個應用程序,並嘗試從我使用MVC在C#中創建的服務讀取Json值。該服務正在返回以下Json響應。org.json.JSONArray無法轉換爲JSONObject ANDROID

[{"empID":"1","Fname":"Khayyam","SurName":"Studenti","DOB":null,"gender":null},{"empID":"2","Fname":"Student 2","SurName":"Zaheer","DOB":null,"gender":null}] 

程序的以下部分是從Web服務獲取值並存儲在字符串中。

_input = new BufferedReader(new InputStreamReader(_urlConnection.getInputStream())); 

String _data; 
StringBuilder _Sb = new StringBuilder(); 

while((_data = _input.readLine())!=null){ 
    _Sb.append(_data); 
    _Sb.append(System.getProperty("line.separator")); 
} 

_RestfulString= _Sb.toString(); 

.....

和的AsyncTask

protected void onPostExecute(Void unused){ 
    JSONObject _response; 
    try{ 
     _response = new JSONObject(_RestfulString); 
     JSONArray _jsonNodes = _response.optJSONArray("rest"); 

     for(int x=0; x< _RestfulString.length();x++){ 
      JSONObject _childNode = _jsonNodes.getJSONObject(x); 
      Log.d("Fname",_childNode.optString("Fname")); 
      txtFname.setText(_childNode.optString("Fname")); 
      txtSname.setText(_childNode.optString("SurName")); 
      txtDOB.setText(_childNode.optString("DOB")); 
     } 

    } 
    catch (Exception exp) { 
     Log.d("Excetpion",exp.getMessage()); 
     _pDialog.hide(); 
    } 
} 

的postExecution只要程序命中

_response = new JSONObject(_RestfulString); 

它提高

Value [{"empID":"1","Fname":"Muhammad Khayyam","SurName":"Qureshii","DOB":null,"gender":null},{"empID":"2","Fname":"Sobia","SurName":"Zaheer","DOB":null,"gender":null}] 

of type org.json.JSONArray cannot be converted to JSONObject 
例外

回答

3

它清楚地顯示輸入在JSONArray中,並且您試圖將其轉換爲JSONObject,並且您期望的JSONObject可能位於0的索引處。請嘗試下面的代碼

JSONArray arr=new JSONArray(_RestfulString); 
_response=arr.getJSONObject(0); 
相關問題