我在 PHP 中的 JSON 输出是这样完成的:
print json_encode(array('rate' => $topcat, 'hometown' => $hometown, 'talk' => $talk));
我的 JSON 输出在我的浏览器中如下所示:
{“率”:“电影”,“家乡”:“西雅图,华盛顿”,“谈话”:“电影”}
在 Java/Android 中,我这样做:
受保护的无效onPostExecute(无效v){
try {
JSONArray jArray = new JSONArray(result);
JSONObject json_data = null;
for (int i = 0; i < jArray.length(); i++) {
json_data = jArray.getJSONObject(i);
Hometown = json_data.getString("hometown");
FavCategory = json_data.getString("rate");
Talk = json_data.getString("talk");
}
} catch (JSONException e1) {
} catch (ParseException e1) {
e1.printStackTrace();
}
if (Hometown.equals("")) {
Hometown = "Not Specified";
}
tvHometown.setText(Hometown);
tvRate.setText(FavCategory);
tvTalk.setText(Talk);
Log.d("Log: ", Hometown + " " + FavCategory + " " + Talk);
}
}
在那个日志上,我得到了这个: Seattle, WA, null, null
谁能明白为什么?
编辑:新的 Java 代码,仍然出现错误:
String homeTown = "", favCategory = "", favTalk = "";
try {
JSONObject jsonData = new JSONObject(result);
homeTown = jsonData.getString("hometown");
favCategory = jsonData.getString("rate");
favTalk = jsonData.getString("talk");
tvHometown.setText(homeTown);
tvRate.setText(favCategory);
tvTalk.setText(favTalk);
} catch (JSONException e1) {
} catch (ParseException e1) {
e1.printStackTrace();
}
我遇到了一个例外:
02-05 08:51:48.078: E/log_tag(22958): Error in http connection org.json.JSONException: Value null of type org.json.JSONObject$1 cannot be converted to JSONArray