Added the ability to deserialize a Map "key" object from a String into a complex Java type.

This commit is contained in:
Joel Leitch 2009-01-06 07:09:19 +00:00
parent 970446e997
commit 02decace26
2 changed files with 23 additions and 4 deletions

View File

@ -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<String, Object> map = constructMapType(typeOfT, context);
Type childType = new TypeInfoMap(typeOfT).getValueType();
Map<Object, Object> map = constructMapType(typeOfT, context);
TypeInfoMap mapTypeInfo = new TypeInfoMap(typeOfT);
for (Map.Entry<String, JsonElement> 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;
}

View File

@ -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<Integer, String> map = new LinkedHashMap<Integer, String>();
map.put(123, "456");
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
String json = gson.toJson(map, typeOfMap);
assertEquals("{\"123\":\"456\"}", json);
}
public void testMapDeserializationWithIntegerKeys() {
Type typeOfMap = new TypeToken<Map<Integer, String>>() {}.getType();
Map<Integer, String> map = gson.fromJson("{\"123\":\"456\"}", typeOfMap);
assertEquals(1, map.size());
assertTrue(map.containsKey(123));
assertEquals("456", map.get(123));
}
public void testParameterizedMapSubclassSerialization() {
MyParameterizedMap<String, String> map = new MyParameterizedMap<String, String>();