15.4. Parsing JSON in Java¶
15.4.1. JSON to Java¶
In this section, the Gson library (i.e., Google’s JSON library) will be used to parse a JSON string into one or more Java objects. To get us started, consider the following data formatted using JSON:
{
"name": "Jay",
"age": 19,
"classes": [
"CSCI 1302",
"CSCI 1730"
]
}
Now, assume that this JSON data is retrieved by a Java program (e.g.,
from the body of an HTTP response to a successful HTTP request) and
that the program now has access to that JSON data via a String
variable named jsonString
. With that in mind, our goal is to
create a Java object containing the same data as the object described
by jsonString
without having to manually parse through it
using String methods like
indexOf
, substring
, etc. Once we have the data in the
form of a Java object, we will be able to interact using Java code,
just like we do with any other kind of object in Java.
To accomplish our goal, we first need to model the JSON data using
one or more Java classes that declare the same set of variables. We
can use existing classes that come with Java when specifying the
variable types, if appropriate (e.g., the name
and age
variables in the JSON data store a string and integer, respectively,
so String
and int
can be used as their data types in
Java). This won’t work for the overall object depicted in the JSON
data as none of the classes that come with Java are designed to
represent that specific kind of object. That is perfectly okay. In
this situation, we just manually create a new Java class ourselves to
represent the object. Since the overall object in the JSON data looks
like it describes an a student, let’s name this new Java class
Student
:
public class Student {
String name;
int age;
String[] classes;
} // Student
Now that we have a Java class named Student
that can be used
to describe Student
objects, we have all the Java classes and
data types that are needed to represent the JSON data using Java
objects. Instead of constructing these objects manually, we instead
call Gson’s
fromJson(String,
Class) method to parse the data from a String
formatted using JSON directly into a new :Student object containing
the desired instance information:
// parse JSON-formatted string into a Student object
Student jay = GSON.<Student>fromJson(jsonString, Student.class);
// inspect the result
System.out.println(jay.name);
System.out.println(jay.age);
System.out.println("Classes:");
for (int i = 0; i < jay.classes.length; i++) {
String className = jay.classes[i];
System.out.println(" - " + className);
} // for
Here is the expected output:
Jay
19
Classes:
- CSCI 1302
- CSCI 1730
- CSCI 2610
15.4.2. Working Example¶
A working copy of the example presented above is included in the starter code for this chapter.