在将 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中文网其他相关文章!