Archive for the ‘Guide – JSON Parsing’ Category

Guide: Android: Parsing JSON Files with Gson and Native Objects:

I see a lot of questions as for how to parse JSON object in android, So I decides to write
a small guide to demonstrate how it’s done. Android platform has build-in tools for dealing
with those parsing tasks so I going to talk about those today. I also going to
show you a basic use of Google’s Gson library.

When we talk about JSON files, important to say that JSON (stand for JavaScript Object Notation) is, and I quote Wikipedia:

“a text-based open standard designed for human-readable data interchange. It is
derived from the JavaScript scripting language for representing simple data structures
and associative arrays, called objects.”

So JSON standard was basically designed to interchange data between different devices
over the internet. There are actually two main structures in JSON files which are Objects and
Arrays. Those will be the objects we will use in our code in order to parse those files.
Lets dive into an example:

Say we received a JSON file that represents a class and a list of students with their grades,
and this file looks like this:

{
    "Class":{
        "Class_Id": "A2",
        "Class_Type": "Science",
        "Class_Student_Count": 23,
        "Class_Studens": [
            {
                "Student_Id": "123456789",
                "Student_Name": "DavStudent_Id",
                "Student_Age": 23,
                "Student_Grades": [
                    { "Course_Name": "Mathematics", "Course_Grade": 95},
                    { "Course_Name": "Biology", "Course_Grade": 80},
                    { "Course_Name": "English", "Course_Grade": 86}
                ]
            },
            {
                "Student_Id": "987654321",
                "Student_Name": "Dan",
                "Student_Age": 25,
                "Student_Grades": [
                    { "Course_Name": "Mathematics", "Course_Grade": 95},
                    { "Course_Name": "Biology", "Course_Grade": 80},
                    { "Course_Name": "English", "Course_Grade": 86}
                ]
            },
            {
                "Student_Id": "123789456",
                "Student_Name": "Smith",
                "Student_Age": 30,
                "Student_Grades": [
                    { "Course_Name": "Mathematics", "Course_Grade": 95},
                    { "Course_Name": "Biology", "Course_Grade": 80},
                    { "Course_Name": "English", "Course_Grade": 86}
                ]
            },
            {
                "Student_Id": "987321654",
                "Student_Name": "Jhon",
                "Student_Age": 18,
                "Student_Grades": [
                    { "Course_Name": "Mathematics", "Course_Grade": 95},
                    { "Course_Name": "Biology", "Course_Grade": 80},
                    { "Course_Name": "English", "Course_Grade": 86}
                ]
            },
            {
                "Student_Id": "789123456",
                "Student_Name": "Leon",
                "Student_Age": 19,
                "Student_Grades": [
                    { "Course_Name": "Mathematics", "Course_Grade": 95},
                    { "Course_Name": "Biology", "Course_Grade": 80},
                    { "Course_Name": "English", "Course_Grade": 86}
                ]
            },
            {
                "Student_Id": "654987321",
                "Student_Name": "Philip",
                "Student_Age": 22,
                "Student_Grades": [
                    { "Course_Name": "Mathematics", "Course_Grade": 95},
                    { "Course_Name": "Biology", "Course_Grade": 80},
                    { "Course_Name": "English", "Course_Grade": 86}
                ]
            }
        ]
    }
}

As you can see this JSON file describes a students class with class details. In addition it
contains a list of class’s students while each one of them contains a list as well with the
student’s related course grades. It’s a fairly simple valid JSON file and at the moment I will
parse only the students list part, but before that I would like to share the following service
with you: http://jsonlint.com/. It will allow you to validate your JSON file and make
sure that what you receive from any web service is in fact a valid JSON file.

1. First we will create the relevant classes for parsing:
Student Class:

public class Student 
{
    private String studentId;
    private String studentName;
    private int studentAge;
    private List<Grade> studentGrades;
     
	public Student() {
		super();
		this.studentGrades = new ArrayList<Grade>();
	}
	public String getStudentId() {
		return studentId;
	}
	public void setStudentId(String studentId) {
		this.studentId = studentId;
	}
	public String getStudentName() {
		return studentName;
	}
	public void setStudentName(String studentName) {
		this.studentName = studentName;
	}
	public int getStudentAge() {
		return studentAge;
	}
	public void setStudentAge(int studentAge) {
		this.studentAge = studentAge;
	}
	public List<Grade> getStudentGrades() {
		return studentGrades;
	}
	public void setStudentGrades(List<Grade> studentGrades) {
		this.studentGrades = studentGrades;
	}
    
	public void addGradeToGradesList(Grade grade)
	{
		this.studentGrades.add(grade);
	}
	@Override
	public String toString() {
		return "Student [studentId=" + studentId + ", studentName="
				+ studentName + ", studentAge=" + studentAge
				+ ", studentGrades=" + studentGrades + "]";
	}	
}

Grade Class:

public class Grade 
{
	private String course;
	private int courseGrade;
	
	public String getCourse() {
		return course;
	}
	public void setCourse(String course) {
		this.course = course;
	}
	public int getCourseGrade() {
		return courseGrade;
	}
	public void setCourseGrade(int courseGrade) {
		this.courseGrade = courseGrade;
	}
	@Override
	public String toString() {
		return "Grade [course=" + course + ", courseGrade=" + courseGrade + "]";
	}	
}

Those classes are really self-explanatory so I’m not going to dwell on them much.

2. Second, I will create the JSON parsing class:

import java.util.ArrayList;
import java.util.List;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import android.util.Log;

public class JSONParsingClass 
{
	private static final String TAG = JSONParsingClass.class.getSimpleName();
	
	//static final String for parsed elements
	//Class elements
	public static final String STUDENTS_LIST_ELEMENT = "Class_Studens";
	
	//Student elements
	public static final String STUDENT_ID = "Student_Id";
	public static final String STUDENT_NAME = "Student_Name";
	public static final String STUDENT_AGE = "Student_Age";
	public static final String STUDENT_GRADE_LIST = "Student_Grades";
	public static final String CLASS = "Class";
	
	//Grade elements
	public static final String COURSE_NAME = "Course_Name";
	public static final String COURSE_GRADE = "Course_Grade";

	//Native method for parsing json file
	public static List<Student> NativeJsonParseMethodForStudents(String jsonString) {
		try{
			//Creating list object for storing the parsed students
			List<Student> studentsList = new ArrayList<Student>();
			
			//Creating JSON object from string
			JSONObject json = new JSONObject(jsonString);
			
			//Getting "Class" element from JSON file
			JSONObject classElement = json.getJSONObject(CLASS);

			//Making sure that students list array exists
			if (!classElement.isNull(STUDENTS_LIST_ELEMENT))
			{
				//Getting students array
				JSONArray array = classElement.getJSONArray(STUDENTS_LIST_ELEMENT);
				
				//Creating empty json object for students loop
				JSONObject currentStudent;
				
				//looping all the students and adding them parsed one by one to the list
				for (int i = 0 ; i < array.length() ; i ++){
					currentStudent = array.getJSONObject(i);
					
					//Method to parse students and add them to the list
					addCurrentStudentToStudentsList(currentStudent, studentsList);
				}
				//Returning parsed students list
				return studentsList;
			}
			else
			{
				Log.d(TAG, "Students List is Null");
				return null;
			}
		} catch (Exception e) {
		   	Log.e("EXC", "Error", e);
		   	return null;
		}
	}
	
	//Method to parse students and added them to the list
	private static void addCurrentStudentToStudentsList(JSONObject currentStudent, List<Student> studentsList) 
	{
		//Initializing Student Object
		Student student = new Student();
		
		//Creating empty list for student's grades.
		List<Grade> studentGrades = new ArrayList<Grade>();
		try {
			//Parsing student's details.
			student.setStudentId(currentStudent.getString(STUDENT_ID));
			student.setStudentName(currentStudent.getString(STUDENT_NAME));
			student.setStudentAge(currentStudent.getInt(STUDENT_AGE));	
			
			//Making sure that student's grades list array exists
			if (!currentStudent.isNull(STUDENT_GRADE_LIST))
			{
				//Getting grades array
				JSONArray array = currentStudent.getJSONArray(STUDENT_GRADE_LIST);
				
				//Creating empty json object for grades loop
				JSONObject currentGrade;
				
				//looping all the student's grades and adding them parsed one by one to the list
				for (int i = 0 ; i < array.length() ; i ++){
					currentGrade = array.getJSONObject(i);
					
					//Method to parse grades and add them to the list
					addCurrentGradeToGradesList(currentGrade, studentGrades);
				}
			}
			//Setting student's grades
			student.setStudentGrades(studentGrades);
			
			//Adding student to the list
			studentsList.add(student);
			Log.d(TAG, "Added student: "+ student.toString()); 
		} catch (JSONException e) {
			Log.e(TAG, "Exception thrown on adding student to students list: "+ e.toString());
			e.printStackTrace();
		}	
	}
	
	//Method to parse grades and add them to the list
	private static void addCurrentGradeToGradesList(JSONObject currentGrade, List<Grade> studentGrades) {
		Grade grade = new Grade();
		Log.d(TAG, "currentGrade object: " + currentGrade.toString());
		try 
		{
			//Parsing grade's details
			grade.setCourse(currentGrade.getString(COURSE_NAME));
			grade.setCourseGrade(currentGrade.getInt(COURSE_GRADE));
			
			//Adding grade to the list
			studentGrades.add(grade);
			
		} catch (JSONException e) {
		Log.e(TAG, "Exception thrown on adding grade to grades list: "+ e.toString());
		e.printStackTrace();
		}
	}	
}

I added a comment above each line of code, So this class should be more then understandable
as well. And basically you are done, you have a parsed list of all the students with their grades
from the JSON file. You can practice by creating the “Class” class and try to parse it and add
the students to it’s list.

Gson Library Usage:

In the next part of this guide I will show you a way to cut down on the written code for parsing
this simple file by using the Gson library, because lets admit it, it’s whole lot of code
for parsing such a simple file.

1. So the first step for using Gson library as with any other library is of course to download it,
head to Gson Download and download the latest version.

2. Next, as before we will have to create the class we are going to populate with the parsed
data, but this time with a small difference:

Student Class for Gson:

import com.google.gson.annotations.SerializedName;

public class Student 
{
    @SerializedName(JSONParsingClass.STUDENT_ID)
    private String studentId;
	
    @SerializedName(JSONParsingClass.STUDENT_NAME)
    private String studentName;
	
    @SerializedName(JSONParsingClass.STUDENT_AGE)
    private int studentAge;
	
    @SerializedName(JSONParsingClass.STUDENT_GRADE_LIST)
    private List<Grade> studentGrades;

    //Rest of code is unchanged...    

Grade Class for Gson:

import com.google.gson.annotations.SerializedName;

public class Grade 
{
    @SerializedName(JSONParsingClass.COURSE_NAME)
    private String course;
	
    @SerializedName(JSONParsingClass.COURSE_GRADE)
    private int courseGrade;
    
    //Rest of code is unchanged...

It possible to omit the Gson annotations if you use the same variable names for the class
parameters as they appear in the JSON file, but because this is not the case those annotations are necessary.

3. Now, I will added another method to my JSONParsingClass:

private static void addCurrentStudentToStudentsListUsingGson(JSONObject currentStudent, List<Student> studentsList) 
{
    Gson gson = new Gson();
    Student student = gson.fromJson(currentStudent.toString(), Student.class);
    studentsList.add(student);
}

4. Finally, I will replace this line of code:

addCurrentStudentToStudentsList(currentStudent, studentsList);

In the

public static List<Student> NativeJsonParseMethodForStudents(String jsonString)

Method, with this line of code:

addCurrentStudentToStudentsListUsingGson(currentStudent, studentsList);

So we basically replaced the two long parsing methods: addCurrentStudentToStudentsList
and addCurrentGradeToGradesList from the first part of this guide with this single 3 lines of
code method: addCurrentStudentToStudentsListUsingGson. And that’s it, Now you can
parse JSON files in your application in the native way or use the Gson library.

One last thing, during the writing of this post, I have created an Android project with all the source
code presented here. You can download this project from here.

Enjoy and stay tuned.

May 18, 2013Emil Adjiev 14 Comments »
FILED UNDER :Guide , Guide - Android Development , Guide - JSON Parsing