15.3. Serializing to JSON in Java

In this section, the Gson library (i.e., Google’s JSON library) will be used to serialize one or more Java objects into a JSON string (i.e., generate JSON using one or more Java objects). To get us started, consider the following simple Java class with member-level declarations that are intentionally left package private to keep the example simple:

public class Student {
    String name;
    int age;
    String[] classes;
} // Student

Now assume that we have access to the following object via a variable named jay:

hide circle
skinparam TitleDontSize 0
skinparam classAttributeIconSize 0
set namespaceSeparator none

map ": String[]" as StringArray {
  0 => "CSCI 1302"
  1 => "CSCI 1730"
  2 => "CSCI 2610"
}

map ": Student" as StudentObject {
  name => "Jay"
  age => 19
  classes *-> StringArray
}

Object Diagram for Object referred to by jay

Under the assumption that jay refers to the Student object depicted above, the following code snippet leverages Gson to serialize the object from what it looks like in memory to the JSON depicted below the code snippet:

Student jay = ...; // constructed to look like the diagram
String jayJson = GSON.toJson(jay);
System.out.println(jayJson);
{
  "name": "Jay",
  "age": 19,
  "classes": [
     "CSCI 1302",
     "CSCI 1730",
     "CSCI 2610"
  ]
}