Prashanth Prashanth - 4 months ago 25
JSON Question

Android JSONObject Conversion

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.

Answer

student is a JSONObject and you have to manage it like a JSONObject. Change

 user = json.getJSONArray("student");

to

 JSONObject user = json.getJSONObject("student");