我正在Android中创建一个应用程序并试图从我使用MVC在C#中创建的服务中读取Json值。该服务正在返回以下Json响应。
[{"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
答案 0 :(得分:3)
可以清楚地看到输入位于JSONObject
,您正试图将其转换为JSONObject
,而您想要的0
可能是JSONArray arr=new JSONArray(_RestfulString);
_response=arr.getJSONObject(0);
的索引。请尝试下面的代码
margin-top: 1em;