Thursday 18 October 2012

How to use GSON API


//A sample pojo for the creation of GSON objects.

package com.json.googlegson.example;

import java.util.ArrayList;
import java.util.List;

public class UserPojo {

 private int age = 5;
 private String name = "Gaurav";

 @SuppressWarnings("serial")
 private List<String> messages = new ArrayList<String>(0) {
  {
   add("WIFE");
   add("FATHER");
   add("MOTHER");
   add("SISTER");
  }
 };

 @Override
 public String toString() {
  return "User [age=" + age + ", name=" + name + ", " + "messages="
    + messages + "]";
 }

 public int getAge() {
  return age;
 }

 public void setAge(int age) {
  this.age = age;
 }

 public String getName() {
  return name;
 }

 public void setName(String name) {
  this.name = name;
 }

 public List<String> getMessages() {
  return messages;
 }

 public void setMessages(List<String> messages) {
  this.messages = messages;
  }

}



//Sample Program to create a json object file using GSON API.

package com.json.googlegson.example;

import java.io.FileWriter;
import java.io.IOException;
import com.google.gson.Gson;

public class ToJSONExampleUsingGSON {

 public static void main(String rags[]) {

  UserPojo userPojo = new UserPojo();
  Gson gson = new Gson();
  String json = gson.toJson(userPojo);

  try {
             FileWriter fWriter = new FileWriter("C:\\UserPojoUsingGson.json");
             fWriter.write(json);
             fWriter.close();
          System.out.println("*****File Written Successfully*****");
         } catch (IOException ioe) {
       ioe.printStackTrace();
      }
   }
}

//Sample Program to read a json object file using GSON API.

package com.json.googlegson.example;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import com.google.gson.Gson;

public class FromJSONExampleUsingGSON {

 public static void main(String args[]) {

  Gson gson = new Gson();
  try {
            BufferedReader br = new BufferedReader(new FileReader("C:\\UserPojoUsingGson.json"));
            UserPojo userPojo = gson.fromJson(br, UserPojo.class);
            System.out.println(userPojo);
          } catch (IOException ioe) {
          ioe.printStackTrace();
        }
     }
}

Note:- To execute this above example gson-2.1.jar is required.

No comments:

Post a Comment