From 02decace2685790a1a826756bfe7951e56b3ef81 Mon Sep 17 00:00:00 2001 From: Joel Leitch Date: Tue, 6 Jan 2009 07:09:19 +0000 Subject: [PATCH] Added the ability to deserialize a Map "key" object from a String into a complex Java type. --- .../com/google/gson/DefaultTypeAdapters.java | 9 +++++---- .../com/google/gson/functional/MapTest.java | 18 ++++++++++++++++++ 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/gson/src/main/java/com/google/gson/DefaultTypeAdapters.java b/gson/src/main/java/com/google/gson/DefaultTypeAdapters.java index c8d41154..9810b2b6 100644 --- a/gson/src/main/java/com/google/gson/DefaultTypeAdapters.java +++ b/gson/src/main/java/com/google/gson/DefaultTypeAdapters.java @@ -485,11 +485,12 @@ final class DefaultTypeAdapters { throws JsonParseException { // Use ObjectConstructor to create instance instead of hard-coding a specific type. // This handles cases where users are using their own subclass of Map. - Map map = constructMapType(typeOfT, context); - Type childType = new TypeInfoMap(typeOfT).getValueType(); + Map map = constructMapType(typeOfT, context); + TypeInfoMap mapTypeInfo = new TypeInfoMap(typeOfT); for (Map.Entry entry : json.getAsJsonObject().entrySet()) { - Object value = context.deserialize(entry.getValue(), childType); - map.put(entry.getKey(), value); + Object key = context.deserialize(new JsonPrimitive(entry.getKey()), mapTypeInfo.getKeyType()); + Object value = context.deserialize(entry.getValue(), mapTypeInfo.getValueType()); + map.put(key, value); } return map; } diff --git a/gson/src/test/java/com/google/gson/functional/MapTest.java b/gson/src/test/java/com/google/gson/functional/MapTest.java index ea2501cd..98f9586a 100755 --- a/gson/src/test/java/com/google/gson/functional/MapTest.java +++ b/gson/src/test/java/com/google/gson/functional/MapTest.java @@ -13,6 +13,7 @@ * See the License for the specific language governing permissions and * limitations under the License. */ + package com.google.gson.functional; import java.lang.reflect.Type; @@ -125,6 +126,23 @@ public class MapTest extends TestCase { assertEquals(1, map.size()); assertNull(map.get(null)); } + + public void testMapSerializationWithIntegerKeys() { + Map map = new LinkedHashMap(); + map.put(123, "456"); + Type typeOfMap = new TypeToken>() {}.getType(); + String json = gson.toJson(map, typeOfMap); + + assertEquals("{\"123\":\"456\"}", json); + } + + public void testMapDeserializationWithIntegerKeys() { + Type typeOfMap = new TypeToken>() {}.getType(); + Map map = gson.fromJson("{\"123\":\"456\"}", typeOfMap); + assertEquals(1, map.size()); + assertTrue(map.containsKey(123)); + assertEquals("456", map.get(123)); + } public void testParameterizedMapSubclassSerialization() { MyParameterizedMap map = new MyParameterizedMap();