sinamdar2015 / google-gson

Automatically exported from code.google.com/p/google-gson
0 stars 0 forks source link

Upper bounds of typed collections is not enforced #406

Open GoogleCodeExporter opened 9 years ago

GoogleCodeExporter commented 9 years ago
1. Create a Model class containing a typed list with an Upper Bound (so a class 
with a member List<O extends MyObject> objects;)
2. Create a dedicated TypeAdapterFactory for MyObject and its subclasses
3. Instantiate the model and serialize it-->All goes well
3. Deserialize the serialized string-->The List is now a list of LinkedHashMap 
although the code specifically says that it is a List of something that extends 
MyObject.

The List type adapter does not call the dedicated TypeAdapterFactory and uses 
its internal ObjectTypeAdapter factory which deserializes everything as 
LinkedHashMap although the List is clearly typed with at least a MyObject class 
or any of its subclasses.
When looking more in depth, this is due to the order of the factories in the 
Gson class. The ObjectTypeAdapter factory is just before the dedicated 
TypeAdapterFactory and since Gson resolved 'O extends MyObject' as a rawType 
Object brather than MyObject, I never get called.

For me there are two issues here:
1) Gson should enforce the upper bound and therefore the rawType of 'O extends 
MyObject' should be 'MyObject' and not 'Object' (although this is arguable but 
I don't want to debate on that, so just implementing 2) would be already a very 
good start)
2) The ObjectTypeFactory should be one of the last factory in the list to 
consider allowing user factories to override its default behaviour.

This happens with gson 2.1.

You will find attached a Maven/Eclipse project that reproduces the issue (if 
you don't use Maven, simply add the gson jar as a library of the project and 
use src/main/java as a source folder.
Main class is com.agilebirds.model.Test.

Thanks.

Original issue reported on code.google.com by guillaum...@agilebirds.com on 7 Feb 2012 at 10:02

Attachments:

GoogleCodeExporter commented 9 years ago

Original comment by limpbizkit on 9 Feb 2012 at 4:04

GoogleCodeExporter commented 9 years ago
FYI, you can work around this issue by registering a type adapter for the 
offending type.

Original comment by limpbizkit on 18 Mar 2012 at 6:05