【发布时间】:2014-04-28 18:23:15
【问题描述】:
我正在尝试以 JSON 格式从我的数据库中检索数据,并将该结果设置为 JSONObject,然后显示在文本视图中。
代码如下:
private class ShowDBActivity3 extends AsyncTask<Void, Void, String>{
protected String doInBackground(Void... voids){
String s = "";
ArrayList<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>();
nameValuePairs.add(new BasicNameValuePair("username", username));
try {
HttpClient httpclient = new DefaultHttpClient();
HttpPost httppost = new HttpPost("URL");
httppost.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httppost);
HttpEntity entity = response.getEntity();
is = entity.getContent();
Log.e("pass 1", "connection success ");
} catch (Exception e) {
Log.e("Fail 1", e.toString());
Toast.makeText(getApplicationContext(), "Invalid IP Address",
Toast.LENGTH_LONG).show();
}
try {
BufferedReader reader = new BufferedReader
(new InputStreamReader(is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
while ((line = reader.readLine()) != null) {
sb.append(line + "\n");
}
is.close();
result = sb.toString();
Log.e("pass 2", "connection success ");
} catch (Exception e) {
Log.e("Fail 2", e.toString());
}
try {
Log.e("This is the result: ", result.toString());
JSONObject jArray = new JSONObject(result);
String title = jArray.getString("title");
String rating = jArray.getString("rating");
String username = jArray.getString("username");
s = "Movie: " + title + "\n" +
"Rating: " + rating + "\n";
return s;
} catch (Exception e) {
Log.e("Fail 3", e.toString());
}
return s;
}
protected void onPostExecute(String s){
show.setText(s);
}
}
这是返回的结果:
结果如下:﹕[{"0":"16","id":"16","1":"绿巨人","title":"绿巨人","2":" 7","rating":"7","3":"tlong3","username":"tlong3"},{"0":"19","id":"19","1":"无敌浩克","title":"无敌浩克","2":"3","rating":"3","3":"tlong3","username":"tlong3"},{" 0":"20","id":"20","1":"Testtt","title":"Testtt","2":"6","rating":"6","3" :"Tlong3","用户名":"Tlong3"}]
...由于某种原因无法转换为 JSONObject。这是错误:
04-28 13:14:25.372 20099-20830/com.android.movies E/Fail 3: org.json.JSONException: Value [{"3":"tlong3","id":"16", "2":"7","username":"tlong3","title":"绿巨人","1":"绿巨人","0":"16","rating":"7"} ,{"3":"tlong3","id":"19","2":"3","username":"tlong3","title":"无敌浩克","1":"The不可思议的绿巨人","0":"19","rating":"3"},{"3":"Tlong3","id":"20","2":"6","username": org.json.JSONArray 类型的 "Tlong3","title":"Testtt","1":"Testtt","0":"20","rating":"6"}] 无法转换为 JSONObject
【问题讨论】: