使用 Java 中的 Gson 自定義例項建立器?
在將 JSON 字串解析為 Java 物件或從 Java 物件解析為 JSON 字串時,Gson 預設透過呼叫預設建構函式來嘗試建立 Java 類例項。如果 Java 類不包含預設建構函式,或我們希望在建立 Java 物件時進行一些初始配置,則需要建立和註冊我們自己的例項建立器。
我們可以在 Gson 中使用InstanceCreator介面建立自定義例項建立器,並且需要實現createInstance(Type type) 方法。
語法
T createInstance(Type type)
示例
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; } }
輸出
Course[ course1 = Core Java, course2 = Advanced Java, technology = Java ]
廣告