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 authors inside the Book
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.
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 browser. 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
):
Plain Old Java Object (POJO)
POJO is short for Plain Old Java Object; it's a cute way of referring to simple classes like Book
and Author
that are free of any special restriction or requirement that might be imposed by using a third-part library or a framework.
POJO
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:
Write and run a simple demo for this and check out the JSON file that stores the Author
object.
info
Gson can do a lot! Feel free to explore its "User Guide".
- Martin Fowler is known for his famous book "Refactorig" which is pretty popular in the software engineering community.↩
- https://www.martinfowler.com/bliki/POJO.html↩