2017-01-22 7 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

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

とすぐにプログラムが

_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); 
関連する問題