JamesDeCarlo / google-gson

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

Generiz-ed type are not well serialized #350

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?
1. Create a generic-ized class containing a generic-ized collection
2. Try to serialize it via Gson.toJson()
Example:
    public class MyObject<T> {
        public List<T> foo;
    }

MyObject<String> o = new MyObject<String>();
o.foo = new ArrayList<String>();
o.foo.add("bar"); o.foo.add("baz");
new Gson().toJson(o); // returns { "foo": [{},{}] } instead of { "foo": 
["bar","baz"] }

What is the expected output? What do you see instead?
I would expect that GSon would consider each instances of my collection, or 
eventually, an exception saying it is not yet implemented.
Instead, the serialization seems to be ok, and I have an "empty object" for 
each of the collection elements, instead of the plain representation of the 
object.

What version of the product are you using? On what operating system?
GSon 1.7.1

Please provide any additional information below.
Unit test attached reproducing the problem.

Original issue reported on code.google.com by fcamb...@gmail.com on 28 Jul 2011 at 3:15

Attachments:

GoogleCodeExporter commented 9 years ago
You need to use the two-arg form of Gson.toJson():
  new Gson().toJson(o, new TypeToken<<MyObject<String>>() {});
Otherwise GSON doesn't have the type information that it needs to do a good job.

Original comment by limpbizkit on 29 Jul 2011 at 4:23

GoogleCodeExporter commented 9 years ago
Ok I just learnt I was confused between compile time and runtime valorization 
of parameteried types (if we use List<String> as an attribute in a class it 
will work well).

However, wouldn't be worth to throw an exception instead of  serializing an 
empty object when we are in such a case where no TypeToken is given on a 
generic type ?

Original comment by fcamb...@gmail.com on 29 Jul 2011 at 7:10

GoogleCodeExporter commented 9 years ago
@fcamblor yeah, I agree that our behavior is confusing. Often the current 
behavior is useful when you're serializing a giant graph of things and you 
don't necessarily care about everything.

Original comment by limpbizkit on 29 Jul 2011 at 1:25

GoogleCodeExporter commented 9 years ago
Issue 351 has been merged into this issue.

Original comment by limpbizkit on 2 Aug 2011 at 6:22