在將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 ]
以上是在Java中使用Gson建立自訂實例的方法?的詳細內容。更多資訊請關注PHP中文網其他相關文章!