java-gson-反序列化包含列表的对象
作者:互联网
我是gson的新手,正在尝试研究如何反序列化对象中的列表.
错误消息提示我为Player创建了InstanceCreator.
但是在实施时,我发现反序列化的对象包含一个Player列表,其名称字段设置为“默认值”,而不是从json字符串中选取值.所以我现在想知道这种方法是否正确.
这是我正在研究的模型的简化,但突出了问题所在…
public interface Player {
String name();
}
public class PlayerImpl implements Player {
private String name;
public PlayerImpl(String name) {
this.name = name;
}
public String name() { return this.name; }
}
public interface Team {
...
}
public class TeamImpl implements Team {
String name;
List<Player> players = new ArrayList<>();
public TeamImpl(String teamName) { this.name = teamName; }
...
}
我有一个简单的测试来创建一个拥有2名球员的新球队
Team t = new TeamImpl("teamname");
t.addPlayer(new PlayerImpl("p1"));
t.addPlayer(new PlayerImpl("p2"));
Gson gson = new Gson();
String json = gson.toJson(t);
这将创建以下json字符串:
{"name":"teamname","players":[{"name":"p1"},{"name":"p2"}]}
但是,当我反序列化json字符串时…
Team t2 = gson.fromJson(json, TeamImpl.class);
我收到以下错误:
java.lang.RuntimeException: Unable to invoke no-args constructor for interface com.example.Player. Register an InstanceCreator with Gson for this type may fix this problem.
at com.google.gson.internal.ConstructorConstructor$14.construct(ConstructorConstructor.java:226)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:210)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:41)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:82)
at com.google.gson.internal.bind.CollectionTypeAdapterFactory$Adapter.read(CollectionTypeAdapterFactory.java:61)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:129)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:220)
at com.google.gson.Gson.fromJson(Gson.java:887)
at com.google.gson.Gson.fromJson(Gson.java:852)
at com.google.gson.Gson.fromJson(Gson.java:801)
at com.google.gson.Gson.fromJson(Gson.java:773)
at com.example.data.JsonDataTests.test_team_json(JsonDataTests.java:62)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at org.junit.internal.runners.TestMethodRunner.executeMethodBody(TestMethodRunner.java:99)
at org.junit.internal.runners.TestMethodRunner.runUnprotected(TestMethodRunner.java:81)
at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
at org.junit.internal.runners.TestMethodRunner.runMethod(TestMethodRunner.java:75)
at org.junit.internal.runners.TestMethodRunner.run(TestMethodRunner.java:45)
at org.junit.internal.runners.TestClassMethodsRunner.invokeTestMethod(TestClassMethodsRunner.java:71)
at org.junit.internal.runners.TestClassMethodsRunner.run(TestClassMethodsRunner.java:35)
at org.junit.internal.runners.TestClassRunner$1.runUnprotected(TestClassRunner.java:42)
at org.junit.internal.runners.BeforeAndAfterRunner.runProtected(BeforeAndAfterRunner.java:34)
at org.junit.internal.runners.TestClassRunner.run(TestClassRunner.java:52)
at org.junit.runner.JUnitCore.run(JUnitCore.java:121)
at com.intellij.junit4.JUnit4IdeaTestRunner.startRunnerWithArgs(JUnit4IdeaTestRunner.java:68)
at com.intellij.rt.execution.junit.IdeaTestRunner$Repeater.startRunnerWithArgs(IdeaTestRunner.java:51)
at com.intellij.rt.execution.junit.JUnitStarter.prepareStreamsAndStart(JUnitStarter.java:237)
at com.intellij.rt.execution.junit.JUnitStarter.main(JUnitStarter.java:70)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:497)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:147)
Caused by: java.lang.UnsupportedOperationException: Interface can't be instantiated! Interface name: com.example.Player
at com.google.gson.internal.UnsafeAllocator.assertInstantiable(UnsafeAllocator.java:117)
at com.google.gson.internal.UnsafeAllocator.access$000(UnsafeAllocator.java:31)
at com.google.gson.internal.UnsafeAllocator$1.newInstance(UnsafeAllocator.java:49)
at com.google.gson.internal.ConstructorConstructor$14.construct(ConstructorConstructor.java:223)
... 35 more
解决方法:
Gson清楚地报告它无法实例化接口.为了使其成为可能,您可以注册一个自定义类型适配器,该适配器将知道如何序列化一个实例并反序列化它.
final class InterfaceSerializer<T>
implements JsonSerializer<T>, JsonDeserializer<T> {
private final Class<T> implementationClass;
private InterfaceSerializer(final Class<T> implementationClass) {
this.implementationClass = implementationClass;
}
static <T> InterfaceSerializer<T> interfaceSerializer(final Class<T> implementationClass) {
return new InterfaceSerializer<>(implementationClass);
}
@Override
public JsonElement serialize(final T value, final Type type, final JsonSerializationContext context) {
final Type targetType = value != null
? value.getClass() // `type` can be an interface so Gson would not even try to traverse the fields, just pick the implementation class
: type; // if not, then delegate further
return context.serialize(value, targetType);
}
@Override
public T deserialize(final JsonElement jsonElement, final Type typeOfT, final JsonDeserializationContext context) {
return context.deserialize(jsonElement, implementationClass);
}
}
然后配置您的Gson实例(每个应用程序一次,Gson是不可变的且线程安全的):
Gson gson = new GsonBuilder()
.registerTypeAdapter(Player.class, interfaceSerializer(PlayerImpl.class))
.registerTypeAdapter(Team.class, interfaceSerializer(TeamImpl.class))
.create();
请注意,现在甚至Team t2 = gson.fromJson(json,Team.class);会工作(没有TeamImpl.class.
也许基于意见,但…我强烈建议您不要绑定到Gson中的接口. Gson的唯一责任是在与您的应用程序一起使用的业务/价值对象之间进行序列化和反序列化.看一下描述问题的Data Transfer Object模式,并为将数据与应用程序之间来回传输的对象建议分段.有了这个,您可以从DTO中删除接口,这样就不需要像这样的适配器,也不必关心DTO类如何声明和注释.知道您可能拥有TeamDto和PlayerDto甚至无法实现您的接口,但可以清楚地绑定数据,例如,TeamDate类. }. DTO可以轻松转换为简单的实现,也可以轻松地从中构造.
标签:json-deserialization,gson,java 来源: https://codeday.me/bug/20191026/1935471.html