我正在测试RuntimeTypeAdapterFactoryTest:
它在原始示例测试用例(testRuntimeTypeAdapter())中工作得很好:
但是如果注册的类型是空的,我会在RuntimeTypeAdapterFactory中得到一个NPE异常。扩展上面的原始示例:
static class Wallet {
BillingInstrument payment;
}
Wallet wallet = new Wallet();
// wallet.payment = new Card("Jo", 123); // leave wallet.payment uninitialized.
gson.toJson(wallet); // throws NPE如果我初始化wallet.payment,那么序列化就能正常工作。下面是堆栈跟踪:
Exception in thread, java.lang.NullPointerException
at com.me.test.RuntimeTypeAdapterFactory$1.write(RuntimeTypeAdapterFactory.java:218)
at com.google.gson.internal.bind.TypeAdapterRuntimeTypeWrapper.write(TypeAdapterRuntimeTypeWrapper.java:68)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$1.write(ReflectiveTypeAdapterFactory.java:91)
at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.write(ReflectiveTypeAdapterFactory.java:206)
at com.google.gson.Gson.toJson(Gson.java:595)
...这一点如下:
有没有人遇到过这种情况并找到了解决办法?默认情况下,Gson应该忽略序列化null值,所以我不确定为什么在我的示例中它会尝试序列化wallet.payment。
谢谢
发布于 2019-04-28 03:28:27
此问题已在2.4版之前的this commit中得到修复
发布于 2015-04-20 17:28:46
遇到了同样的问题。这个修复方法对我很有效:
(RuntimeTypeAdapterFactory.java)
@Override public void write(JsonWriter out, R value) throws IOException {
if(value!=null) {
Class<?> srcType = value.getClass();
String label = subtypeToLabel.get(srcType);
@SuppressWarnings("unchecked") // registration requires that subtype extends T
TypeAdapter<R> delegate = (TypeAdapter<R>) subtypeToDelegate.get(srcType);
if (delegate == null) {
throw new JsonParseException("cannot serialize " + srcType.getName()
+ "; did you forget to register a subtype?");
}
JsonObject jsonObject = delegate.toJsonTree(value).getAsJsonObject();
if (jsonObject.has(typeFieldName)) {
throw new JsonParseException("cannot serialize " + srcType.getName()
+ " because it already defines a field named " + typeFieldName);
}
JsonObject clone = new JsonObject();
clone.add(typeFieldName, new JsonPrimitive(label));
for (Map.Entry<String, JsonElement> e : jsonObject.entrySet()) {
clone.add(e.getKey(), e.getValue());
}
Streams.write(clone, out);
}else{
out.nullValue();
}https://stackoverflow.com/questions/27759968
复制相似问题