JSON File Reading and Writing

Short term storage with JSON and Java

March 12, 2019, 9:38 p.m.

It is sometimes necessary to implement a short term storage solution to move data to and from memory in a piece of software. There are certainly libraries available like Redis that allow for similar, albeit more cumbersome, functionality by utilizing the memory of another machine (perhaps on the cloud). However, we may run into a situation where utilizing another machine and dealing with networking and other possible dependencies is not ideal. This calls for some classic File based storage.

JSON is a very well known format for describing and transmitting data throughout programs. There are many java frameworks built for working with JSON and this makes it an ideal candidate to describe our data for File based storage. Due to all these frameworks it can be a bit confusing knowing exactly where to start with this task, but the following will serve as a simple blueprint to getting started.

First, make sure to add Google's GSON to your project as a dependency:

<dependency>
    <groupId>com.google.code.gson</groupId>
    <artifactId>gson</artifactId>
    <version>2.8.5</version>
</dependency>

Now it is possible to leverage GSON to easily read and write JSON in Java. It may seem counterintuitive, but it is actually simpler to think about reading the JSON from a File prior to writing it. In order to do this we will utilize the FileReader and JSONParser:

try {
    FileReader reader = new FileReader("file.json");
    JSONParser jsonParser = new JSONParser();
    JSONObject json = (JSONObject) jsonParser.parse(reader);
 } catch (ParseException | IOException e) {
     //Oops, something went wrong...handle accordingly
 }

As we've just seen it is simple to read JSON from a File, but how do we get that JSON there in the first place? That part is every bit as simple as the last:

JSONObject json = new JSONObject();
// Here is where we would put some data into the JSONObject
...
try {
    Files.write(Paths.get("file.json"), json.toJSONString().getBytes());
} catch (IOException e) {
    //Oops, something went wrong...handle accordingly
}

With this blueprint you are merely a couple of simple methods away from utilizing plain, old Files for short term data storage.

Comments about JSON File Reading and Writing

No one has left a comment yet, be the first to voice your opinion on JSON File Reading and Writing!