From 4cb1b88115d1290cacf38436dc3e7ec983e99e5a Mon Sep 17 00:00:00 2001 From: Jesse Wilson Date: Thu, 29 Dec 2011 07:27:33 +0000 Subject: [PATCH] Test for registerTypeHierarchyAdapter() using Date.class Fixes issue 352. --- .../functional/CustomTypeAdaptersTest.java | 24 +++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java b/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java index 9343e6cc..4c2ae706 100644 --- a/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java +++ b/gson/src/test/java/com/google/gson/functional/CustomTypeAdaptersTest.java @@ -30,6 +30,7 @@ import com.google.gson.common.TestTypes.BagOfPrimitives; import com.google.gson.common.TestTypes.ClassWithCustomTypeConverter; import com.google.gson.reflect.TypeToken; +import java.util.Date; import junit.framework.TestCase; import java.lang.reflect.Type; @@ -393,6 +394,17 @@ public class CustomTypeAdaptersTest extends TestCase { assertNull(actual.wrappedData); } + // Test created from Issue 352 + public void testRegisterHierarchyAdapterForDate() { + Gson gson = new GsonBuilder() + .registerTypeHierarchyAdapter(Date.class, new DateTypeAdapter()) + .create(); + assertEquals("0", gson.toJson(new Date(0))); + assertEquals("0", gson.toJson(new java.sql.Date(0))); + assertEquals(new Date(0), gson.fromJson("0", Date.class)); + assertEquals(new java.sql.Date(0), gson.fromJson("0", java.sql.Date.class)); + } + private static class DataHolder { final String data; @@ -428,4 +440,16 @@ public class CustomTypeAdaptersTest extends TestCase { return new DataHolder(jsonElement.getAsString()); } } + + private static class DateTypeAdapter implements JsonSerializer, JsonDeserializer { + public Date deserialize(JsonElement json, Type typeOfT, + JsonDeserializationContext context) throws JsonParseException { + return typeOfT == Date.class + ? new Date(json.getAsLong()) + : new java.sql.Date(json.getAsLong()); + } + public JsonElement serialize(Date src, Type typeOfSrc, JsonSerializationContext context) { + return new JsonPrimitive(src.getTime()); + } + } }