-
Notifications
You must be signed in to change notification settings - Fork 4.3k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
[bug] sub class field missing during serialization if collection's element type is a WildcardType #1870
Comments
There is #170 which seems to exactly describe your problem, but it was merged into #231 despite that issue apparently covering a completely different use case. The underlying issue is that A workaround for this would be to create a custom class RuntimeTypeAdapterFactory implements TypeAdapterFactory {
public static final RuntimeTypeAdapterFactory INSTANCE = new RuntimeTypeAdapterFactory();
private RuntimeTypeAdapterFactory() { }
@Override
public <T> TypeAdapter<T> create(Gson gson, TypeToken<T> type) {
TypeAdapter<T> delegate = gson.getDelegateAdapter(this, type);
return new TypeAdapter<T>() {
@Override
public T read(JsonReader in) throws IOException {
return delegate.read(in);
}
@Override
public void write(JsonWriter out, T value) throws IOException {
if (value == null) {
// Let compile-time type adapter handle `null`
delegate.write(out, null);
}
else {
@SuppressWarnings("unchecked")
TypeToken<T> runtimeType = (TypeToken<T>) TypeToken.get(value.getClass());
// Get adapter for runtime type
TypeAdapter<T> delegate = gson.getDelegateAdapter(RuntimeTypeAdapterFactory.this, runtimeType);
delegate.write(out, value);
}
}
};
}
} This factory would then have to be registered after all other factories and adapters on the Gson gson = new GsonBuilder()
.registerTypeAdapterFactory(RuntimeTypeAdapterFactory.INSTANCE)
.create(); This will decrease performance and might have unintended side effects when you actually want to use the adapter for the compile-time type in some cases. |
Thanks, it works for me |
I am serializing a list like this:
I find that the fields of TestBeanSub is missed in the serialized json.
You can try my example code:
Output json :
The text was updated successfully, but these errors were encountered: