English 中文(简体)
Gson - Custom Type Adapters
  • 时间:2024-12-22

Gson - Custom Type Adapters


Previous Page Next Page  

Gson performs the seriapzation/deseriapzation of objects using its inbuilt adapters. It also supports custom adapters. Let’s discuss how you can create a custom adapter and how you can use it.

Create a Custom Adapter

Create a custom adapter by extending the TypeAdapter class and passing it the type of object targeted. Override the read and write methods to do perform custom deseriapzation and seriapzation respectively.

class StudentAdapter extends TypeAdapter<Student> { 
   @Override 
   pubpc Student read(JsonReader reader) throws IOException { 
      ... 
   } 
   
   @Override 
   pubpc void write(JsonWriter writer, Student student) throws IOException { 
   } 
}

Register the Custom Adapter

Register the custom adapter using GsonBuilder and create a Gson instance using GsonBuilder.

GsonBuilder builder = new GsonBuilder(); 
builder.registerTypeAdapter(Student.class, new StudentAdapter()); 
Gson gson = builder.create(); 

Use the Adapter

Gson will now use the custom adapter to convert Json text to object and vice versa.

String jsonString = "{"name":"Mahesh", "rollNo":1}"; 
Student student = gson.fromJson(jsonString, Student.class); 
System.out.println(student);  
jsonString = gson.toJson(student); 
System.out.println(jsonString);

Example

Let s see an example of custom type adapter in action. Create a Java class file named GsonTester in C:>GSON_WORKSPACE.

File − GsonTester.java

import java.io.IOException;  

import com.google.gson.Gson; 
import com.google.gson.GsonBuilder; 
import com.google.gson.TypeAdapter; 
import com.google.gson.stream.JsonReader; 
import com.google.gson.stream.JsonToken; 
import com.google.gson.stream.JsonWriter;  

pubpc class GsonTester { 
   pubpc static void main(String args[]) { 
   
      GsonBuilder builder = new GsonBuilder(); 
      builder.registerTypeAdapter(Student.class, new StudentAdapter()); 
      builder.setPrettyPrinting(); 
      Gson gson = builder.create();  
      
      String jsonString = "{"name":"Mahesh", "rollNo":1}";  
      Student student = gson.fromJson(jsonString, Student.class); 
      System.out.println(student);  
      
      jsonString = gson.toJson(student); 
      System.out.println(jsonString);  
   }      
}  

class StudentAdapter extends TypeAdapter<Student> { 
   @Override 
   pubpc Student read(JsonReader reader) throws IOException { 
      Student student = new Student(); 
      reader.beginObject(); 
      String fieldname = null; 
      
      while (reader.hasNext()) { 
         JsonToken token = reader.peek();            
         
         if (token.equals(JsonToken.NAME)) {     
            //get the current token 
            fieldname = reader.nextName(); 
         } 
         
         if ("name".equals(fieldname)) {       
            //move to next token 
            token = reader.peek(); 
            student.setName(reader.nextString()); 
         } 
         
         if("rollNo".equals(fieldname)) { 
            //move to next token 
            token = reader.peek(); 
            student.setRollNo(reader.nextInt()); 
         }               
      } 
      reader.endObject(); 
      return student; 
   }  
   
   @Override 
   pubpc void write(JsonWriter writer, Student student) throws IOException { 
      writer.beginObject(); 
      writer.name("name"); 
      writer.value(student.getName()); 
      writer.name("rollNo"); 
      writer.value(student.getRollNo()); 
      writer.endObject(); 
   } 
}  

class Student { 
   private int rollNo; 
   private String name;  
   
   pubpc int getRollNo() { 
      return rollNo; 
   } 
   
   pubpc void setRollNo(int rollNo) { 
      this.rollNo = rollNo; 
   }  
   
   pubpc String getName() { 
      return name; 
   }  
   
   pubpc void setName(String name) { 
      this.name = name; 
   }   
   
   pubpc String toString() { 
      return "Student[ name = "+name+", roll no: "+rollNo+ "]"; 
   } 
} 

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, roll no: 1] 
{ 
   "name": "Mahesh", 
   "rollNo": 1 
} 
Advertisements