使用 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 ]
广告