Skip to content

Implement POJO Persister With Gson

Storing data in key-value format has its advantages and disadvantages. For example, you can easily change the contents in a text editor. You can also easily make mistakes like misspelling a key. On a more general note, the Properties library class is particularly useful for those classes that contain a few attributes. It is difficult to use it to, for example, store a collection of objects. Moreover, the resulting data file is flat, which makes storing complex structures awkward (e.g. if there was a list of reviews inside the Course class). Furthermore, through the use of Properties, the data types are not specified. It is, therefore, possible to edit the files and, for instance, insert text where numbers should be. A potential solution is to store data in JSON format.

What is JSON?

JSON stands for "JavaScript Object Notation". It is a lightweight format for storing and transporting data, in particular when data is sent from a server to a web page. I recommend watching the (first half of the) following video to learn more about the JSON format.

Google's Gson

Gson is a Java serialization/deserialization library (developed at Google) to convert Java Objects into JSON and back. To use it, add the following line to the dependencies of your project (build.gradle):

1
implementation 'com.google.code.gson:gson:2.8.6'

Plain Old Java Object (POJO)

POJO is short for Plain Old Java Object; it's a cute way of referring to simple classes like Course that are free of any special restriction or requirement that might be imposed by using a third-part library or a framework.

POJO

The term was coined by Martin Fowler, Rebecca Parsons and Josh MacKenzie. In their own words: "we wondered why people were so against using regular objects in their systems and concluded that it was because simple objects lacked a fancy name. So we gave them one, and it's caught on very nicely."1

Gson helps us to directly write a POGO to a file and read it back; it literally takes one statement to do so and as such it helps to reduce the amount of code you have to write:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
public class GsonCoursePersister implements Persister<Course>{
  private final static String STORE = "Store.json";
  private Gson gson = new Gson();

  @Override
  public void serialize(Course course) throws IOException {
    FileWriter fw = new FileWriter(STORE);
    gson.toJson(course, fw);
    fw.close();
  }

  @Override
  public Course deserialize() throws IOException {
    FileReader fr = new FileReader(STORE);
    Course course = gson.fromJson(fr, Course.class);
    fr.close();
    return course;
  }
}

Write and run a simple demo for this and check out the JSON file that stores the Course object.

Note

Gson can do a lot! Feel free to explore its "User Guide".