我在尝试序列化包含java.nio.file.Path
的Object
时得到java.lang.StackOverflowError
甚至当我写道:
public class PathConverter implements JsonDeserializer<Path>, JsonSerializer<Path> {
@Override
public Path deserialize(JsonElement jsonElement, Type type, JsonDeserializationContext jsonDeserializationContext) throws JsonParseException {
return Paths.get(jsonElement.getAsString());
}
@Override
public JsonElement serialize(Path path, Type type, JsonSerializationContext jsonSerializationContext) {
return new JsonPrimitive(path.toString());
}
}
并应用它:
String json = new GsonBuilder()
.registerTypeAdapter(Path.class, new PathConverter())
.create()
.toJson(constructorSetup, new TypeToken<ConstructorSetup>() {}.getType());
我仍然不能序列化这个类:
public class ConstructorSetup {
private Path appIconMimmapDirPathOnPc;
}
Stacktrace:(在pastebin上完整)
Exception in thread "main" java.lang.StackOverflowError
at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:375)
at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
...
at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:380)
at com.google.gson.internal.$Gson$Types.resolve($Gson$Types.java:355)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:117)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:72)
at com.google.gson.Gson.getAdapter(Gson.java:356)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:82)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:81)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:118)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:72)
at com.google.gson.Gson.getAdapter(Gson.java:356)
...
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.<init>(ReflectiveTypeAdapterFactory.java:82)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.createBoundField(ReflectiveTypeAdapterFactory.java:81)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.getBoundFields(ReflectiveTypeAdapterFactory.java:118)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory.create(ReflectiveTypeAdapterFactory.java:72)
at com.google.gson.Gson.getAdapter(Gson.java:356)
有什么办法吗?
1条答案
按热度按时间ebdffaop1#
你的问题是
Path
是一个interface
。假设你使用了Paths.get("/")
,它将在我的Windows PC上创建类似WindowsPath
的示例。现在,你必须告诉GSON如何实现这种类型:另一种可以使用的方法是
registerTypeHierarchyAdapter
:typeHierarchyAdapter的目的是覆盖当你想要一个类型的所有子类型的相同表示时的情况,这正是你使用
Path
的情况。