From 912add077989dc06977fe31209d4d8d125bce8d4 Mon Sep 17 00:00:00 2001 From: Jesse Wilson Date: Mon, 14 Mar 2011 22:14:35 +0000 Subject: [PATCH] (Failing) test cases for registering competing types. --- .../functional/TypeHierarchyAdapterTest.java | 38 +++++++++++++++++++ 1 file changed, 38 insertions(+) diff --git a/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java b/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java index ecdd13d9..24ba2241 100644 --- a/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java +++ b/gson/src/test/java/com/google/gson/functional/TypeHierarchyAdapterTest.java @@ -23,6 +23,7 @@ import com.google.gson.JsonDeserializer; import com.google.gson.JsonElement; import com.google.gson.JsonObject; import com.google.gson.JsonParseException; +import com.google.gson.JsonPrimitive; import com.google.gson.JsonSerializationContext; import com.google.gson.JsonSerializer; import java.lang.reflect.Type; @@ -115,6 +116,43 @@ public final class TypeHierarchyAdapterTest extends TestCase { ((Manager) company.ceo.minions[2]).minions[1].userid); } + public void testRegisterSubtypeFirst() { + Gson gson = new GsonBuilder() + .registerTypeHierarchyAdapter(Employee.class, new EmployeeAdapter()) + .registerTypeHierarchyAdapter(Manager.class, new ManagerAdapter()) + .create(); + + Manager manager = new Manager(); + manager.userid = "inder"; + + String json = gson.toJson(manager, Manager.class); + assertEquals("\"inder\"", json); + Manager copied = gson.fromJson(json, Manager.class); + assertEquals(manager.userid, copied.userid); + } + + public void testRegisterSupertypeFirst() { + GsonBuilder builder = new GsonBuilder() + .registerTypeHierarchyAdapter(Manager.class, new ManagerAdapter()) + .registerTypeHierarchyAdapter(Employee.class, new EmployeeAdapter()); + try { + builder.create(); + fail(); + } catch (IllegalArgumentException expected) { + } + } + + static class ManagerAdapter implements JsonSerializer, JsonDeserializer { + public Manager deserialize(JsonElement json, Type typeOfT, JsonDeserializationContext context) { + Manager result = new Manager(); + result.userid = json.getAsString(); + return result; + } + public JsonElement serialize(Manager src, Type typeOfSrc, JsonSerializationContext context) { + return new JsonPrimitive(src.userid); + } + } + static class EmployeeAdapter implements JsonSerializer, JsonDeserializer { public JsonElement serialize(Employee employee, Type typeOfSrc, JsonSerializationContext context) {