在 Java 中使用 Gson 自定义实例创建器?
javajsonobject oriented programmingprogramming
在将 JSON 字符串解析为 Java 对象或从 Java 对象解析 JSON 字符串时,默认情况下,Gson 会尝试通过调用默认构造函数来创建 Java 类的实例。如果 Java 类不包含默认构造函数,或者我们想在创建 Java 对象时进行一些初始配置,则需要创建并注册我们自己的实例创建器。
我们可以使用 InstanceCreator接口在 Gson 中创建自定义实例创建器,并需要实现 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 ]