You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
ConstructorConstructor.newDefaultImplementationConstructor(Type, Class<? super T>) breaks symmetry #1708
The method com.google.gson.internal.ConstructorConstructor.newDefaultImplementationConstructor(Type, Class<? super T>) breaks symmetry.
Normally it is desired that if you can serialize obj as A, then you should be able to deserialize it as A again. This is however not possible if A extends / implements one of the types checked in newDefaultImplementationConstructor and does not have a no-arg constructor.
Example:
static class MyList extends ArrayList<Integer>{
// Any constructor with parameters to prevent default constructor
public MyList(int i) {}
}
public void testCustomList() {
Gson gson = new Gson();
MyList list = new MyList(1);
list.add(1);
String json = gson.toJson(list);
// java.lang.ClassCastException: Cannot cast java.util.ArrayList to MyList
gson.fromJson(json, MyList.class);
}
The proper fix would be to have newDefaultImplementationConstructor only create instances if the requested type is the type it creates (e.g. it creates ArrayList and ArrayList is requested) or if the requested type is a supertype of the created one (e.g. it creates ArrayList and List is requested).
Similarly CollectionTypeAdapterFactory would have to be adjusted to only support these types and types for which a constructor has been registered or types which have a default (= no-arg) constructor.
This would in theory not cause any issues if people already serialized and deserialized their objects and therefore the types they are using are matching the above stated requirements.
However, there might be cases where people only serialize objects (such as MyList in the example above), which would break with such a change.
Would it make sense to instead introduce an option to GsonBuilder to prevent serialization which is not symmetric? So people can catch such issues early?
Activity
Marcono1234 commentedon Jul 28, 2022
Maybe a duplicate of / closely related to #419