简介
有些类,无法使用无参构造函数生成对象,而 Gson 默认依赖无参构造函数,此时会反序列化失败。
解决方案是用 InstanceCreator 实现类的对象生成器,注册到 Gson 中。
代码示例
package org.example;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.google.gson.InstanceCreator;
import lombok.Data;
import org.junit.jupiter.api.Test;
import java.lang.reflect.Type;
public class TestInstanceCreator {
@Data
public static class UserInfo {
private String name01;
private String name02;
private UserInfo() {
throw new RuntimeException("禁止用无参构造函数");
}
public UserInfo(String name01, String name02) {
this.name01 = name01;
this.name02 = name02;
}
}
// 会报错
@Test
public void test_01() {
Gson gson = new GsonBuilder().create();
String jsonStr = "{\"name01\": \"李白\"}";
// 下面的反序列化会报错
UserInfo userInfo = gson.fromJson(jsonStr, UserInfo.class);
System.out.println(userInfo);
}
// 使用 InstanceCreator 解决问题
@Test
public void test_02() {
Gson gson = new GsonBuilder().registerTypeAdapter(UserInfo.class, new InstanceCreator<UserInfo>() {
@Override
public UserInfo createInstance(Type type) {
return new UserInfo("a", "b");
}
}).create();
String jsonStr = "{\"name01\": \"李白\"}";
UserInfo userInfo = gson.fromJson(jsonStr, UserInfo.class);
System.out.println(userInfo);
// 以上代码输出: TestInstanceCreator.UserInfo(name01=李白, name02=b)
}
}