Reputation: 341
I have a JSON
file want to retrieve details from it and just display it in text view.
I get values for message and success but not for other i.e., student and details
My JSON:
{
"message":"Thank you for your patience.",
"student":{
"name":"aaaa",
"mark":"55",
"dob":"10-09-1990"},
"details":{
"fathername":"bbbb",
"mothername":"ccccc",
"address":"xxxxxx"},
"success":true
}
My Java Code
@Override
protected JSONObject doInBackground(String... args) {
JSONParser jParser = new JSONParser();
// Getting JSON from URL
JSONObject json = jParser.getJSONFromUrl(url);
return json;
}
@Override
protected void onPostExecute(JSONObject json) {
try {
// Getting JSON Array
// Storing JSON item in a Variable
String success = json.getString("success"); // I get values for both of these
String message = json.getString("message");
String StudentName = null;
// I Tried This/*
user = json.getJSONArray("student");
for (int i = 0; i < user.length(); i++) {
email = user.getJSONObject(i).getString("name");
}*/
//Set JSON Data in TextView
uid.setText(success);
name1.setText(message);
email1.setText(email);
} catch (JSONException e) {
e.printStackTrace();
}
}
I tried above code but get a error
01-06 18:26:15.120: W/System.err(2110): org.json.JSONException: Value {"name":"aaaa","mark":"55","dob":"10-09-1990"} at student of type org.json.JSONObject cannot be converted to JSONArray
Help me to solve this issue.
Upvotes: 1
Views: 224
Reputation: 589
{ "message":"Thank you for your patience.", "student":{ "name":"aaaa", "mark":"55", "dob":"10-09-1990"}, "details":{ "fathername":"bbbb", "mothername":"ccccc", "address":"xxxxxx"}, "success":true }
Android Code :
JsonObject jsonobj = new JsonObject("your json String");
String message = jsonobj.getString("message");
String success = jsonobj.getString("success");
JsonObject studentObj = jsonobj.getJsonObject("student");
String name = studentObj.getString("name");
String mark= studentObj.getString("mark");
JsonObject detailsObj = jsonobj.getJsonObject("details");
String fathername= detailsObj.getString("fathername");
String mothername= detailsObj.getString("mothername");
Upvotes: 0
Reputation: 157437
student is a JSONObject and you have to manage it like a JSONObject. Change
user = json.getJSONArray("student");
to
JSONObject user = json.getJSONObject("student");
Upvotes: 3
Reputation: 133560
user = json.getJSONArray("student");
student is not a jsonarray
"student":{
student is a jsononbject
So change
JSONObject user = json.getJSONObject("student");
Then
String name = user.getString("name");
@Override
protected void onPostExecute(JSONObject json)
super.onPostExecute(json); // missing
// although this does not lead to any error
Upvotes: 3