diff --git a/gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java b/gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java index e5ace902..f5050dae 100644 --- a/gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java +++ b/gson/src/test/java/com/google/gson/functional/CustomDeserializerTest.java @@ -16,8 +16,6 @@ package com.google.gson.functional; -import java.lang.reflect.Type; - import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.google.gson.JsonDeserializationContext; @@ -28,6 +26,8 @@ import com.google.gson.JsonParseException; import junit.framework.TestCase; +import java.lang.reflect.Type; + /** * Functional Test exercising custom deserialization only. When test applies to both * serialization and deserialization then add it to CustomTypeAdapterTest. @@ -106,4 +106,38 @@ public class CustomDeserializerTest extends TestCase { return new DataHolder(dataString + SUFFIX); } } + + public void testJsonTypeFieldBasedDeserialization() { + String json = "{field1:'abc',field2:'def',__type__:'SUB_TYPE1'}"; + Gson gson = new GsonBuilder().registerTypeAdapter(MyBase.class, new JsonDeserializer() { + public MyBase deserialize(JsonElement json, Type pojoType, + JsonDeserializationContext context) throws JsonParseException { + String type = json.getAsJsonObject().get(MyBase.TYPE_ACCESS).getAsString(); + return context.deserialize(json, SubTypes.valueOf(type).getSubclass()); + } + }).create(); + SubType1 target = (SubType1) gson.fromJson(json, MyBase.class); + assertEquals("abc", target.field1); + } + private static class MyBase { + static final String TYPE_ACCESS = "__type__"; + } + private enum SubTypes { + SUB_TYPE1(SubType1.class), + SUB_TYPE2(SubType2.class); + private final Type subClass; + private SubTypes(Type subClass) { + this.subClass = subClass; + } + public Type getSubclass() { + return subClass; + } + } + private static class SubType1 extends MyBase { + String field1; + } + private static class SubType2 extends MyBase { + @SuppressWarnings("unused") + String field2; + } }