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

时间:2015-08-11 20:56:39

标签: java json gson

我有一个界面

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);时,它会返回null。 jsonString是UTF_8 String。

是否因为UVW类中使用的接口?如果是,我该如何反序化这类?

1 个答案:

答案 0 :(得分:4)

您需要告诉Gson在反序列化XYZ时使用ABCYou 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