这是一个缩小范围的示例,非常荒谬,但说明了问题。
以下代码:
import java.util.*;
import com.google.gson.*;
class X {}
class SomeType {
private Map <X, String> map;
public SomeType() {
this.map = new HashMap<X, String>();
map.put(new X(), "b");
}
}
public class FooMain {
private static Gson gson = new GsonBuilder().serializeNulls().create();
public static void main(String args[]) throws Exception {
String foo = gson.toJson(new SomeType(), SomeType.class);
System.out.println(foo); // line 20
SomeType st = gson.fromJson(foo, SomeType.class); // line 21
}
}
失败:
[java] Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 20
[java] at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:176)
[java] at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.read(TypeAdapterRuntimeTypeWrapper.java:40)
[java] at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:187)
[java] at com.google.gson.internal.bind.MapTypeAdapterFactory$Adapter.read(MapTypeAdapterFactory.java:146)
[java] at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.read(ReflectiveTypeAdapterFactory.java:93)
[java] at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:172)
[java] at com.google.gson.Gson.fromJson(Gson.java:795)
[java] at com.google.gson.Gson.fromJson(Gson.java:761)
[java] at com.google.gson.Gson.fromJson(Gson.java:710)
[java] at com.google.gson.Gson.fromJson(Gson.java:682)
[java] at FooMain.main(FooMain.java:21)
[java] Caused by: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 20
[java] at com.google.gson.stream.JsonReader.expect(JsonReader.java:339)
[java] at com.google.gson.stream.JsonReader.beginObject(JsonReader.java:322)
[java] at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:165)
[java] ... 10 more
而第 20 行打印:
{"map":{"X@185b10b":"b"}}