【问题标题】:why do two seemingly identical hashmaps have different behavior when serialized by gson?为什么两个看似相同的哈希图在被 gson 序列化时具有不同的行为?
【发布时间】:2018-08-10 04:18:43
【问题描述】:

输入:

public static void main(String[] args) {

    final String key = "some key";
    final String value = "some value";

    Map<String, String> map1 = new HashMap<String, String>(){{put(key, value);}};
    System.out.println(new Gson().toJson(map1) + " " + map1.get(key));

    Map<String, String> map2 = new HashMap<>();
    map2.put(key, value);
    System.out.println(new Gson().toJson(map2) + " " + map2.get(key));
}

输出:

null some value
{"some key":"some value"} some value

Process finished with exit code 0

【问题讨论】:

标签: java hashmap gson


【解决方案1】:

对于map1,您创建了一个匿名子类。假设你的类包含main() 被称为ExampleClass,那么:

System.out.println(map1.getClass().getName())

打印出来:

ExampleClass$1

而打印 map2 的类会产生:

java.util.HashMap

至于 Gson 不序列化它的确切原因 - Gson 使用类名来查找转换器。如果您改为使用以下方法对其进行序列化:

System.out.println(new Gson().toJson(map1, HashMap.class));

...它按预期工作。

【讨论】:

猜你喜欢
  • 2013-03-26
  • 2013-04-20
  • 2016-04-27
  • 1970-01-01
  • 2012-08-13
  • 2015-05-29
  • 1970-01-01
  • 1970-01-01
  • 2013-02-08
相关资源
最近更新 更多