Home  >  Article  >  Java  >  Way to create custom instance using Gson in Java?

Way to create custom instance using Gson in Java?

WBOY
WBOYforward
2023-09-05 11:57:06807browse

Way to create custom instance using Gson in Java?

When parsing a JSON string to or from a Java object, by default Gson attempts to resolve it by calling the default constructor to create an instance of a Java class. If the Java class does not contain a default constructor or we want to do some initial configuration when creating a Java object, we need to create and register our own instance creator.

We can create a custom instance creator in Gson using InstanceCreatorinterface and need to implement 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 ]

The above is the detailed content of Way to create custom instance using Gson in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete