2017-01-22 70 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); 
相关问题