我得到错误:
Exception in thread "main" com.google.gson.JsonParseException:
Expecting object found: "com.shagie.app.SimpleMap$Data@24a37368"
当尝试反序列化使用非平凡键的 Map 时:
package com.shagie.app;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import java.util.HashMap;
public class SimpleMap {
public static void main(String[] args) {
Wrapper w = new Wrapper();
w.m.put(new Data("f", 1), new Data("foo", 3));
w.m.put(new Data("b", 2), new Data("bar", 4));
GsonBuilder gb = new GsonBuilder();
gb.setPrettyPrinting();
Gson g = gb.create();
String json = g.toJson(w);
System.out.println(json);
w = g.fromJson(json, Wrapper.class);
System.out.println(w.m.isEmpty());
}
static public class Wrapper {
HashMap<Data, Data> m = new HashMap<Data, Data>();
}
static public class Data {
String s;
Integer i;
public Data(String arg, Integer val) { s = arg; i = val; }
}
}
这会序列化为 json:
{ "m": { "com.shagie.app.SimpleMap$Data@24a37368": { "s": "foo", "i": 3 }, "com.shagie.app.SimpleMap$Data@66edc3a2": { "s": "bar", "i": 4 } } }
可以看到尝试序列化的 key ,但肯定不是以可以反序列化的方式。
如何序列化此对象以便反序列化?
最佳答案
我在尝试解决这个难题时发现了以下内容:Issue 210: Cannot serialize or deserialize Maps with complex keys .
For any internet travelers from the future (like myself)... you can enable this functionality in GSON 2.* with the enableComplexMapKeySerialization() method on GsonBuilder.
启用后, map 将被序列化(并正确反序列化)为 [key, value] 数组的数组:
{"m":[[{"s":"f", "i",1}, {"s":"foo", "i":3}], [{"s":"b", "i",2}, {"s":"bar", "i":4}]]}
关于java - 使用 Gson 反序列化映射键需要一个对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21209240/