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 simple JSON string that has been manually constructed using Java code:
String nl = "\n";
String jsonString = "{ " + nl
+ " \"name\": \"Jay\"," + nl
+ " \"age\": 19, " + nl
+ " \"classes\": [ " + nl
+ " \"CSCI 1302\", " + nl
+ " \"CSCI 1730\" " + nl
+ " ] " + nl
+ "} ";
System.out.println(jsonString);
Under the assumption that jsonString
refers to the JSON string
depicted above, we need to create one or more Java classes to
represent the object(s) depected in the JSON string:
public class Student {
String name;
int age;
String[] classes;
} // Student
With that in mind, the following code snippet leverages Gson to parse the JSON string from what it looks like in JSON to one or more Java objects:
// parse JSON-formatted string into a Student object
Student jay = GSON.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.