我在PHP中的JSON输出是这样完成的:
print json_encode(array('rate' => $topcat, 'hometown' => $hometown, 'talk' => $talk));我的JSON输出在我的浏览器中如下所示:
{“评分”:“电影”,“家乡”:“西雅图,华盛顿州”,“谈话”:“电影”}
在Java/Android中,我这样做:
保护无效onPostExecute(Void ){
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发布于 2013-02-05 02:43:19
除了PHP词汇表之外,这个JSON的顶层元素是:
{"rate":"Movies","hometown":"Seattle, WA","talk":"Movies"}是数组。{}是一种死而复生的礼物。
改变这个
JSONArray jArray = new JSONArray(result);对此:
JSONObject jsonData = new JSONObject(result);然后从那里出发:
String hometown = jsonData.getString("hometown");
String favCategory = jsonData.getString("rate");
String talk = jsonData.getString("talk");注意,作为一种良好的Java风格,我如何使用lowerCamelCased变量名。
发布于 2013-02-05 09:49:40
您应该有一个方括号来表示它是一个JSONArray,您的结果在JSONObject中,如果您想获取每个JSONArray的数据,您的结果应该更像下面所示
{"rate": ["samplevalue","samplevalue"],"Movies" : ["samplevalue","samplevalue"],"hometown":["Seattle, WA"],"talk":["Movies"]}https://stackoverflow.com/questions/14699301
复制相似问题