How can I get Gson to deserialize an interface type? [duplicate]

寵の児 提交于 2020-07-18 22:17:31

问题


I have an interface

public interace ABC {
}

Implementation of this is as follows:

public class XYZ implements ABC {
    private Map<String, String> mapValue;
    public void setMapValue( Map<String, String> mapValue) {
        this.mapValue = mapValue;
    }  

    public  Map<String, String> getMapValue() {
        return this.mapValue
    }
}

I want to deserialize a class using Gson which is implemented as

public class UVW {
    ABC abcObject;
}

when I try to deserialize it like gson.fromJson(jsonString, UVW.class); it returns me null. jsonString is UTF_8 String.

Is it because of interface used in UVW class? If yes, how do I deserialize such class?


回答1:


You need to tell Gson to use XYZ when it deserializes ABC. You can do this using a TypeAdapterFactory.

Briefly, thus:

public class ABCAdapterFactory implements TypeAdapterFactory {
  private final Class<? extends ABC> implementationClass;

  public ABCAdapterFactory(Class<? extends ABC> implementationClass) {
     this.implementationClass = implementationClass;
  }

  @SuppressWarnings("unchecked")
  @Override
  public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
    if (!ABC.class.equals(type.getRawType())) return null;

    return (TypeAdapter<T>) gson.getAdapter(implementationClass);
  }
}

Here is a complete working test harness that illustrates this example:

public class TypeAdapterFactoryExample {
  public static interface ABC {

  }

  public static class XYZ implements ABC {
    public String test = "hello";
  }

  public static class Foo {
    ABC something;
  }

  public static void main(String... args) {
    GsonBuilder builder = new GsonBuilder();
    builder.registerTypeAdapterFactory(new ABCAdapterFactory(XYZ.class));
    Gson g = builder.create();

    Foo foo = new Foo();
    foo.something = new XYZ();

    String json = g.toJson(foo);
    System.out.println(json);
    Foo f = g.fromJson(json, Foo.class);
    System.out.println(f.something.getClass());
  }
}

Output:

{"something":{"test":"hello"}}
class gson.TypeAdapterFactoryExample$XYZ


来源:https://stackoverflow.com/questions/31951779/how-can-i-get-gson-to-deserialize-an-interface-type

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!