Computer >> Máy Tính >  >> Lập trình >> Java

Trình tạo phiên bản tùy chỉnh sử dụng Gson trong Java?


Trong khi phân tích cú pháp Chuỗi JSON đến hoặc từ đối tượng Java, Theo mặc định, Gson cố gắng tạo một phiên bản của lớp Java bằng cách gọi hàm tạo mặc định . Trong trường hợp lớp Java không chứa hàm tạo mặc định hoặc chúng tôi muốn thực hiện một số cấu hình ban đầu trong khi tạo các đối tượng Java, chúng tôi cần tạo và đăng ký trình tạo phiên bản của riêng mình.

Chúng tôi có thể tạo trình tạo phiên bản tùy chỉnh trong Gson bằng cách sử dụng InstanceCreator giao diện và cần triển khai createInstance ( Loại loại ) phương pháp.

Cú pháp

T createInstance(Type type)

Ví dụ

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;
   }
}

Đầu ra

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