【问题标题】:How do I Gson deserializes an interface to a specific implementation?我如何 Gson 将接口反序列化为特定实现?
【发布时间】:2015-08-24 11:39:54
【问题描述】:

如果我尝试反序列化下面的 Wrapper 类,该类旨在保存类 HashMap 的实例,则反序列化器将替换 com.google.gson.internal.LinkedTreeMap 的类,这是不需要的。

如何确保字段的实际类型是我想要的,即HashMap

这是一个 MCVE 来说明我在问什么:

public class HashMapTry {
    public static class Wrapper {
        public String title = "My Title";
        public Map<String, String> map = new HashMap<String,String>();
    }

    public static void main(String[] args) {
        Wrapper wrapper = new Wrapper();
        Wrapper wrapper2;

        wrapper.map.put("vertical", "1, 0");
        wrapper.map.put("horizontal", "0, 1");

        GsonBuilder gb = new GsonBuilder()
                .enableComplexMapKeySerialization()
                .serializeNulls()
                .setPrettyPrinting()
                .setVersion(1.0)
                .setDateFormat("yyyy.MM.dd HH:mm:ss");

        Gson g = gb.create();

        String json = g.toJson(wrapper);
        System.out.println(json);

        wrapper2 = g.fromJson(json, Wrapper.class);
        System.out.println(wrapper2.map.getClass());
    }
}

输出:

{
  "title": "My Title",
  "map": {
    "horizontal": "0, 1",
    "vertical": "1, 0"
  }
}
class com.google.gson.internal.LinkedTreeMap

【问题讨论】:

    标签: java json gson deserialization


    【解决方案1】:

    只需在 Wrapper 类中将其声明为 HashMap。 Gson 不喜欢反序列化到接口默认,因为它必须弄清楚要反序列化到哪个类。如果是某个随机接口(例如interface MyInterface),它实际上会导致问题,因为该接口没有默认行为,您必须指定它,您可以通过注册TypeAdapter 来完成。

    但是,对于这种情况来说,这太复杂了。只需在您的包装类中将其称为HashMap只有在实现无关紧要时才对接口进行编程,但如果它确实很重要则对实现进行编程,这显然是这里的情况。

    public static class Wrapper {
      public String title = "My Title";
    
      public HashMap<String, String> map = new HashMap<String, String>();
    }
    

    输出:

    {
      "title": "My Title",
      "map": {
        "horizontal": "0, 1",
        "vertical": "1, 0"
      }
    }
    class java.util.HashMap
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-11-04
      • 1970-01-01
      相关资源
      最近更新 更多