English 中文(简体)
Gson - Object Serialization
  • 时间:2024-12-22

Gson - Object Seriapzation


Previous Page Next Page  

Let s seriapze a Java object to a Json file and then read that Json file to get the object back. In this example, we ve created a Student class. We ll create a student.json file which will have a json representation of Student object.

Example

Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File - GsonTester.java

import java.io.BufferedReader; 
import java.io.FileNotFoundException; 
import java.io.FileReader; 
import java.io.FileWriter; 
import java.io.IOException;  

import com.google.gson.Gson; 
import com.google.gson.GsonBuilder;  

pubpc class GsonTester { 
   pubpc static void main(String args[]) { 
   
      GsonTester tester = new GsonTester(); 
      try { 
         Student student = new Student(); 
         student.setAge(10); 
         student.setName("Mahesh"); 
         tester.writeJSON(student);  
         Student student1 = tester.readJSON(); 
         System.out.println(student1); 
      } 
      catch(FileNotFoundException e) { 
         e.printStackTrace(); 
      } 
      catch(IOException e) { 
         e.printStackTrace();
      } 
   } 
   
   private void writeJSON(Student student) throws IOException { 
      GsonBuilder builder = new GsonBuilder(); 
      Gson gson = builder.create(); 
      FileWriter writer = new FileWriter("student.json");   
      writer.write(gson.toJson(student));   
      writer.close(); 
   }  
   
   private Student readJSON() throws FileNotFoundException { 
      GsonBuilder builder = new GsonBuilder(); 
      Gson gson = builder.create(); 
      BufferedReader bufferedReader = new BufferedReader(
         new FileReader("student.json"));   
      
      Student student = gson.fromJson(bufferedReader, Student.class); 
      return student; 
   } 
} 

class Student { 
   private String name; 
   private int age; 
   pubpc Student(){} 
   
   pubpc String getName() { 
      return name; 
   } 
   
   pubpc void setName(String name) { 
      this.name = name; 
   } 
   
   pubpc int getAge() { 
      return age; 
   } 
   
   pubpc void setAge(int age) { 
      this.age = age; 
   } 
   
   pubpc String toString() { 
      return "Student [ name: "+name+", age: "+ age+ " ]";
   }  
}

Verify the result

Compile the classes using javac compiler as follows −

C:GSON_WORKSPACE>javac GsonTester.java

Now run the GsonTester to see the result −

C:GSON_WORKSPACE>java GsonTester

Verify the Output

Student [ name: Mahesh, age: 10 ]
Advertisements