guochaiqi / google-gson

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

Serialized HashMap is different if inside another class #294

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
Serializing a HashMap yields different results if it is an object in another 
class.
Code sample:

Gson gson = new Gson();
Object test = new String[] {"this", "is", "a", "test"};
Map<String, Object> hash = new HashMap<String, Object>();
hash.put("othertest", "othertest");
hash.put("test", test);
NamedClass nc = new NamedClass("test", hash);

System.out.println(gson.toJson(hash));
System.out.println(gson.toJson(nc));

This is NamedClass:
public class NamedClass
{
    private String id;
    private Map<String, Object> attributes;

    NamedClass() {}

    public NamedClass(String id, Map<String, Object> attributes)
    {
        this.id = id;
        this.attributes = attributes;
    }
}

What is the expected output? What do you see instead?
This produces:
{"test":["this","is","a","test"],"othertest":"othertest"}  (Great!)
{"id":"test","attributes":{"test":{},"othertest":"othertest"}}  (Oh no, the 
array inside the hashmap now reads "{}")

While I would expect the second line to serialize the hashmap as smartly as it 
does on the first line:
{"id":"test","attributes":{"test":["this","is","a","test"],"othertest":"othertes
t"}}  (Cool, now I see the array here as well)

What version of the product are you using? On what operating system?
gson 1.6 on Windows XP

I need the Map to be <String, Object> because it may contain multivalued as 
well as single valued values (String vs String[]).
I have written a custom serializer to "fix" this, but I believe that should be 
the default behavior...

Original issue reported on code.google.com by crau...@gmail.com on 7 Mar 2011 at 9:45

GoogleCodeExporter commented 9 years ago
Fixed in 828.

Original comment by joel.leitch@gmail.com on 20 Apr 2011 at 10:32

GoogleCodeExporter commented 9 years ago
could you please send me the link for the fix.... or send me the link for (
svn 828) a jar file for this fix... I need code please send me asap..... thank 
you 

Original comment by ravi4ami...@gmail.com on 3 Oct 2011 at 12:16