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.
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 (
Plain Old Java Object (POJO)
POJO is short for Plain Old Java Object; it's a cute way of referring to simple classes like
Author that are free of any special restriction or requirement that might be imposed by using a third-part library or a framework.
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
Gson can do a lot! Feel free to explore its "User Guide".