Gson - 反序列化包含列表的对象

8
我刚接触gson并试图弄清如何反序列化对象内的列表。
错误信息提示需要为Player创建InstanceCreator,我也这样做了。 但是在实现时,我发现反序列化的对象包含一个名为"default value"的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);

I get the following error:

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

尝试在TeamImpl中使用List<PlayerImpl> players = new ArrayList<>();而不是List<Player> players = new ArrayList<>();,因为接口无法实例化!接口名称:com.example.Player。 - Milaci
4个回答

12

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();

请注意,现在即使没有TeamImpl.class也可以使用Team t2 = gson.fromJson(json, Team.class);
或许这是基于个人意见的,但我强烈建议您不要在Gson中绑定接口。Gson唯一的责任是将您的应用程序所使用的业务/值对象序列化和反序列化。看看数据传输对象模式,它描述了问题并建议为向您的应用程序传输数据的对象进行分离。有了这个,您可以从DTO中删除接口,因此您将不需要像那样的适配器,并且不需要关心DTO类的声明和注释方式。知道您可能会有TeamDtoPlayerDto,甚至不实现您的接口,但明确地绑定数据,例如:class TeamDto { private List<PlayerDto> }。DTO可以轻松转换为简单的实现,并且同样可以从中构建。

0

Gson在反序列化时仅适用于POJO,而不是接口。请使用实现PlayerImpl而非接口Player。还有一些其他库,比如Genson,可以支持您的需求。


0
你有这个错:Caused by: java.lang.UnsupportedOperationException: Interface can't be instantiated! Interface name: com.example.Player,所以你应该在TeamImpl里面建一个列表,像这样`List players = new ArrayList(); 因为在GSON中接口无法被实例化。
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 {

   void addPlayer(PlayerImpl p1);
}


import java.util.ArrayList;
import java.util.List;

public class TeamImpl implements Team {

String name;
List<PlayerImpl> players = new ArrayList<PlayerImpl>();

public TeamImpl(String teamName) { this.name = teamName; }


@Override
public void addPlayer(PlayerImpl p1) {
    this.players.add(p1);
}
}

And the main to test it:
public static void main(String[] args) {

Team t = new TeamImpl("teamname");
t.addPlayer(new PlayerImpl("p1"));
t.addPlayer(new PlayerImpl("p2"));
Gson gson = new Gson();
String json = gson.toJson(t);

System.out.println(json);

Team t2 = gson.fromJson(json, TeamImpl.class);
System.out.println(t2.toString());

}

`


0
通常情况下,当一个类将接口用作字段时,也会引发此异常。特别是在创建树形结构时,很难看出你做错了什么:
class A implements IA{
   IA parent;
   Collection<IA> nodes;
}

IA myimpl = gson.fromJson( data_str, A.class );

其中IA是A类的接口。这段代码将会抛出上述异常。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接