tl  tr
  Home | Tutorials | Articles | Videos | Products | Tools | Search
Interviews | Open Source | Tag Cloud | Follow Us | Bookmark | Contact   
 JSON > GOOGLE GSON > Stream to Bean

Stream to Bean 

Google-gson is a java library from Google for encoding and decoding JSON text. Get the latest binaries from http://code.google.com/p/google-gson/. The following example shows converting a JSON Stream to java bean.

File Name  :  
/GOOGLE_GSON/Student.json 

File Name  :  
com/bethecoder/tutorials/google_gson/common/Student.java 
   
package com.bethecoder.tutorials.google_gson.common;

import java.util.Date;

public class Student {
  private String firstName;
  private String lastName;
  private int age;
  private String hobby;
  private Date dob;

  public Student(String firstName, String lastName, int age, String hobby,
      Date dob) {
    super();
    this.firstName = firstName;
    this.lastName = lastName;
    this.age = age;
    this.hobby = hobby;
    this.dob = dob;
  }
  
  public String getFirstName() {
    return firstName;
  }
  public void setFirstName(String firstName) {
    this.firstName = firstName;
  }
  public String getLastName() {
    return lastName;
  }
  public void setLastName(String lastName) {
    this.lastName = lastName;
  }
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  public String getHobby() {
    return hobby;
  }

  public void setHobby(String hobby) {
    this.hobby = hobby;
  }
  public Date getDob() {
    return dob;
  }
  public void setDob(Date dob) {
    this.dob = dob;
  }

  public String toString() {
    return "Student[ " +
      "firstName = " + firstName +
      ", lastName = " + lastName +
      ", age = " + age +
      ", hobby = " + hobby +
      ", dob = " + dob +
      " ]";
  }
}
   

File Name  :  
com/bethecoder/tutorials/google_gson/tests/Stream2Bean.java 
Author  :  Sudhakar KV
Email  :  [email protected]
   
package com.bethecoder.tutorials.google_gson.tests;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.InputStreamReader;
import java.io.Reader;

import com.bethecoder.tutorials.google_gson.common.Student;
import com.google.gson.Gson;

public class Stream2Bean {

  /**
   @param args
   @throws FileNotFoundException 
   */
  public static void main(String[] argsthrows FileNotFoundException {
    Gson gson = new Gson();
    Reader stdReader = new InputStreamReader(new FileInputStream("Student.json"));
    Student stud = gson.fromJson(stdReader, Student.class);
    System.out.println(stud.toString());   
  }
}
   

It gives the following output,
Student[ firstName = Sriram, lastName = Kasireddi, age = 2, 
	hobby = Singing, dob = Thu May 06 00:00:00 IST 2010 ]



 
  


  
bl  br