shau-lok / google-gson

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

Templated collections of collecctions do not serialize correctly #279

Closed GoogleCodeExporter closed 9 years ago

GoogleCodeExporter commented 9 years ago
What steps will reproduce the problem?

See attached file. The program contains a class with a Map and a Map<String, 
Object>. If a value in the map is a List<String>, it does not serialize 
correctly. This is a problem only with the parametrized type Map<String, 
Object>. The non-parametrized type, Map, serializes correctly.

What is the expected output? What do you see instead?

Expected:
{"map":{"string":"strval","map":{"key-1":"value-1","key-2":"value-2"},"list":["e
lement-1","element-2"]},"pMap":{"string":"strval","map":{"key-1":"value-1","key-
2":"value-2"},"list":["element-1","element-2"]}}

Got:
{"map":{"string":"strval","map":{"key-1":"value-1","key-2":"value-2"},"list":["e
lement-1","element-2"]},"pMap":{"string":"strval","map":{},"list":{}}}

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

Gson version 1.6, Mac OS X 10.6.5

Please provide any additional information below.
Related to Issue 205

FIX

Modify DefaultTypeAdapters.MapTypeAdapter to check if the generic type of the 
value type of the map is Object. If so, use the instance's type.

http://code.google.com/p/google-gson/source/browse/trunk/gson/src/main/java/com/
google/gson/DefaultTypeAdapters.java#649

Workaround:

Define an adapter for Objects:

    private static class ObjectTypeAdapter implements JsonSerializer<Object> {
        public JsonElement serialize(Object src, Type typeOfSrc, JsonSerializationContext context) {

            if (src.getClass() != Object.class) {
                return context.serialize(src, src.getClass());
            }

            return new JsonObject();
        }
    }

Register this with the builder:
Gson gson2 = (new GsonBuilder()).registerTypeAdapter(Object.class, new 
ObjectTypeAdapter()).create();

Original issue reported on code.google.com by anand.ke...@gmail.com on 28 Jan 2011 at 6:38

Attachments:

GoogleCodeExporter commented 9 years ago
I like the suggestion of using the runtime type if the map value type is 
Object. It's unfortunate that you can't specify the actual type on the map.

Original comment by limpbizkit on 21 Mar 2011 at 9:54

GoogleCodeExporter commented 9 years ago
I think this works with 1.7.

Original comment by joel.leitch@gmail.com on 13 Apr 2011 at 9:55

GoogleCodeExporter commented 9 years ago
Verified that this is fixed in 1.7.

Original comment by joel.leitch@gmail.com on 15 Apr 2011 at 5:20