discomarathon / google-gson

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

An Object[] field should be serialized per the actual object types #155

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
http://groups.google.com/group/google-
gson/browse_thread/thread/e4df79a0d0dc8959?hl=en

Original issue reported on code.google.com by inder123 on 10 Sep 2009 at 4:40

GoogleCodeExporter commented 9 years ago
Fixed in r442.

Original comment by joel.leitch@gmail.com on 22 Sep 2009 at 7:12

GoogleCodeExporter commented 9 years ago
Not sure this is completely fixed in the 1.4 version I downloaded from the 
website. 

Suppose I have a class Message with a simple 'id':

    public class Message {
        public String messageId;
    }

and a subclass TextMessage which adds a 'text' field.  

    public class TextMessage extends Message {
        public String text;
    }

Lastly I create a MessageBox class that contains a List<Message> (not 
TextMessage) 
called 'messages':

    public class MessageBox {
        public List<Message> messages;
    }

If I create an instance of MessageBox (called mbox) and populate it's list of 
Messages with TextMessages, then I get the following behaviour:

    gson.toJson(mbox.messages) // serialise the collection directly...
    [{"text":"Hello World!","messageId":"t1"},
     {"text":"Hello World!","messageId":"t2"}]

    gson.toJson(mbox) // serialise the containing MessageBox object...
    {"messages":[{"messageId":"t1"},{"messageId":"t2"}]}

In the seconds example simply containing the List in a parent class has 
reverted back 
to the behaviour of serialising based on the parent class. 

Finally, if I switch the declaration of mbox.messages from List<Message> to 
List<Object>, it all works as expected:

    {"messages":[{"text":"Hello World!","messageId":"t1"},
                 {"text":"Hello World!","messageId":"t2"}]}

Original comment by charles%...@gtempaccount.com on 3 Jun 2010 at 5:45