Monday, February 8, 2016

Converting an Object to/from JSON using GSON (Google API)

Converting an Object to/from JSON using GSON (Google API)

Maven dependency required :

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

DataObject class

public class DataObject {
      private int data1 = 100;
      private int data2 = 200;
      List<String> list = new ArrayList<String>() {
            private static final long serialVersionUID = 1L;
            {
                  add("String 1");
                  add("String 2");
                  add("String 3");
            }
      };

      public String toString() {
            return "DataObject [data1=" + data1 + ", data2=" + data2 + ", list="
                        + list + "]";
      }
}

Class converting Object to/from JSON

public class ObjectToFromJson {

      public static void toJson() {
            DataObject obj = new DataObject();
            Gson gson = new Gson();

            // convert java object to JSON format,
            // and returned as JSON formatted string
            String json = gson.toJson(obj);
            System.out.println(json);

            try {
                  // write converted json data to a file named "file.json"
                  FileWriter writer = new FileWriter("C://workspace//DataStructure//GJson//file.json");
                  writer.write(json);
                  writer.close();

            } catch (IOException e) {
                  e.printStackTrace();
            }
      }
     
      public static void fromJson() {
            Gson gson = new Gson();

            try {

                  BufferedReader br = new BufferedReader(new FileReader(
                              "C://workspace//DataStructure//GJson//file.json"));

                  // convert the json string back to object
                  DataObject obj = gson.fromJson(br, DataObject.class);

                  System.out.println(obj);

            } catch (IOException e) {
                  e.printStackTrace();
            }
      }

     
      public static void main(String[] args) {
            toJson();
            fromJson();
      }

}

Output :

{"data1":100,"data2":200,"list":["String 1","String 2","String 3"]}

DataObject [data1=100, data2=200, list=[String 1, String 2, String 3]]

No comments:

Post a Comment