Reputation: 15734
My JSON output in PHP is done this way:
print json_encode(array('rate' => $topcat, 'hometown' => $hometown, 'talk' => $talk));
My JSON output looks like this in my browser:
{"rate":"Movies","hometown":"Seattle, WA","talk":"Movies"}
in Java/Android I do this:
protected void onPostExecute(Void 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);
}
}
On that Log, I get this: Seattle, WA, null, null
Can anyone see why?
EDIT: New Java Code, still getting error:
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();
}
I am getting an exception:
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
Upvotes: 0
Views: 235
Reputation: 1616
you should have a square bracket to indicate that it is a JSONArray your result is in JSONObject if you want to get the data of each JSONArray your result should be more like this
{"rate": ["samplevalue","samplevalue"],"Movies" : ["samplevalue","samplevalue"],"hometown":["Seattle, WA"],"talk":["Movies"]}
Upvotes: 0
Reputation: 359966
Despite the PHP vocabulary, the top-level element of this JSON:
{"rate":"Movies","hometown":"Seattle, WA","talk":"Movies"}
is an object (a key-value mapping), not an array. The {}
s are a dead giveaway.
Change this
JSONArray jArray = new JSONArray(result);
to this:
JSONObject jsonData = new JSONObject(result);
and go from there:
String hometown = jsonData.getString("hometown");
String favCategory = jsonData.getString("rate");
String talk = jsonData.getString("talk");
Note how, as a matter of good Java style, I use lowerCamelCased
variable names.
Upvotes: 4