Custom instance creator using Gson in Java?


While parsing JSON String to or from Java object, By default Gson try to create an instance of Java class by calling the default constructor. In the case of Java class doesn’t contain default constructor or we want to do some initial configuration while creating Java objects, we need to create and register our own instance creator.

We can create a custom instance creator in Gson using the InstanceCreator interface and need to implement the createInstance(Type type) method.

Syntax

T createInstance(Type type)

Example

import java.lang.reflect.Type;
import com.google.gson.*;
public class CustomInstanceCreatorTest {
   public static void main(String args[]) {
      GsonBuilder gsonBuilder = new GsonBuilder();
      gsonBuilder.registerTypeAdapter(Course.class, new CourseCreator());
      Gson gson = gsonBuilder.create();
      String jsonString = "{'course1':'Core Java', 'course2':'Advanced Java'}";
      Course course = gson.fromJson(jsonString, Course.class);
      System.out.println(course);
   }
}
// Course class
class Course {
   private String course1;
   private String course2;
   private String technology;
   public Course(String technology) {
      this.technology = technology;
   }
   public void setCourse1(String course1) {
      this.course1 = course1;
   }
   public void setCourse2(String course2) {
      this.course2 = course2;
   }
   public String getCourse1() {
      return course1;
   }
   public String getCourse2() {
      return course1;
   }
   public void setTechnology(String technology) {
      this.technology = technology;
   }
   public String getTechnology() {
      return technology;
   }
   public String toString() {
      return "Course[ " +
             "course1 = " + course1 +
             ", course2 = " + course2 +
             ", technology = " + technology +
             " ]";
   }
}
// CourseCreator class
class CourseCreator implements InstanceCreator {
   @Override
   public Course createInstance(Type type) {
      Course course = new Course("Java");
      return course;
   }
}

Output

Course[ course1 = Core Java, course2 = Advanced Java, technology = Java ]

Updated on: 04-Jul-2020

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements