Sunday, May 17, 2020

Reading and Writing JSON to a file


Why GSON?

Nowadays JSON is more frequently used for data representation. There are a lot of libraries to convert java objects into JSON and JSON back to java objects. GSON is very simple to use and it is very easy to integrate also. It doesn't require additional libraries to support.

Integrating GSON with maven

Add the following dependency to inside the pom.xml to integrate GSON into maven

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

Java Object to JSON

Following API will convert any object to JSON String
 public static <T> void toJson(T t, String fileName) throws JsonIOException, IOException {  
      Gson gson = new GsonBuilder()  
                .setPrettyPrinting()  
                .serializeNulls()  
                .create();  
      try(FileWriter writer = new FileWriter(fileName)){  
           String json = gson.toJson(t);  
           LOG.log(json);  
           LOG.log("Writing the json to the file "+fileName);  
           gson.toJson(t, writer);  
      }catch(Exception e) {  
           LOG.log(e);  
      }  
 }  
The above code prints the JSON string and writes it to a file writer.
Gson gson = new GsonBuilder().setPrettyPrinting().serializeNulls() .create();

The above lines will create the formatted JSON string.

The file Writer or Reader should be closed so that the data will be flushed to the file. Instead, you can see the empty file getting created. Either you can close the writer object explicitly or use try with resources as I have used.

JSON to Java Object

The below code reads the JSON file and converts it into a respective Class file.
 public static <T> T fromJson(String fileName, Class<T> t) {  
      Gson gson = new Gson();   
      try(FileReader reader = new FileReader(fileName)){    
           T s = gson.fromJson(reader, t);  
           LOG.log("Reading json from "+ fileName+ " completed.");     
           return s;  
      }catch(Exception e) {    
       LOG.log(e);   
      }   
   return null;  
 }  
I have used Generics to support any kind of class file. The class mostly will be a java bean.

The working code is available in the GitHub 




No comments:

Post a Comment

Reading and Writing JSON to a file

Why GSON? Nowadays JSON is more frequently used for data representation. There are a lot of libraries to convert java objects into JSO...