java-如何让Gson反序列化接口类型?

这个问题已经在这里有了答案:            >            How to handle deserializing with polymorphism?                                    4个
我有一个界面

public interace ABC {
}

的实现如下:

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
    }
}

我想使用实现为的Gson反序列化一个类

public class UVW {
    ABC abcObject;
}

当我尝试反序列化时,例如gson.fromJson(jsonString,UVW.class);.它返回我为空. jsonString是UTF_8字符​​串.

是否由于UVW类中使用的接口?如果是,我如何反序列化此类?

解决方法:

您需要让Gson反序列化ABC时使用XYZ. You can do this using a TypeAdapterFactory.

简要地,因此:

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

这是说明此示例的完整的工作测试工具:

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

输出:

{"something":{"test":"hello"}}
class gson.TypeAdapterFactoryExample$XYZ
上一篇:java-当字段名称以点开头时,将Json转换为Object


下一篇:java-Convertig Json到列表