我已经阅读并尝试了很多关于stackoverflow的例子,然后才询问,但到目前为止还没有运气。我想要做的是解析一个json数组,我从php / mysql回来用于在Android中使用。我的代码可以解决这个问题,我可以将json转换为转换后的字符串:
[{"username":"lawn edge","distance":"0.00766418723166294"},{"username":"bbq","distance":"0.00876051437108357"},{"username":"Tablet","distance":"0.0140815866739065"}]
我试图只提取"用户名"并将它们发送到textview。我尝试过的大多数示例只是生成一个空文本视图,或者它在上面看时会转储整个json字符串。我最接近的是使用以下代码:
private void returnJson() {
// TODO Auto-generated method stub
try {
httpPostproximity = new HttpPost(
"http://vtolblog.com/finddistance.php");
List<NameValuePair> nameValuePairs = new ArrayList<NameValuePair>(3);
nameValuePairs.add(new BasicNameValuePair("lat", lat));
nameValuePairs.add(new BasicNameValuePair("lng", lng));
nameValuePairs.add(new BasicNameValuePair("username", check));
httpPostproximity
.setEntity(new UrlEncodedFormEntity(nameValuePairs));
HttpResponse response = httpclient.execute(httpPostproximity);
HttpEntity entity = response.getEntity();
is = entity.getContent();
} catch (Exception e) {
playerlist.setText("error3");
}
try {
BufferedReader reader = new BufferedReader(new InputStreamReader(
is, "iso-8859-1"), 8);
StringBuilder sb = new StringBuilder();
String line = null;
while ((line = reader.readLine()) != null) {
sb.append(line + "\r\n");
}
is.close();
result = sb.toString();
result.trim();
} catch (Exception e) {
playerlist.setText("error2");
}
try {
JSONObject json_data = new JSONObject(result);
JSONArray jArreglo = new JSONArray(result);
for (int i = 0; i < jArreglo.length(); i++) {
json_data = jArreglo.getJSONObject(i);
Log.i("log_tag", "Player: " + json_data.getString("username"));
// Get an output to the screen
jsonplayers += "\n\t" + jArreglo.getJSONObject(i);
}
} catch (JSONException e) {
Log.e("log_tag", "Error parsing data " + e.toString());
playerlist.setText("Error parsing json");
}
playerlist.setText(jsonplayers);
return;
// end of returnJson()
}
如果我改变了playerlist.setText(结果);它将显示上面引用的json数组,所以我假设代码在那之前是可以的吗? 我离开了吗?如果您还需要其他任何帮助,请提前告知我并提前致谢!
答案 0 :(得分:0)
我认为你在网上获得例外:
JSONObject json_data = new JSONObject(result);
因为结果是JSONArray而不是JSONObject,请尝试评论此行。