diff --git a/gson/src/main/java/com/google/gson/Gson.java b/gson/src/main/java/com/google/gson/Gson.java index 11c202aa..0cb3660e 100644 --- a/gson/src/main/java/com/google/gson/Gson.java +++ b/gson/src/main/java/com/google/gson/Gson.java @@ -392,8 +392,9 @@ public final class Gson { */ @SuppressWarnings("unchecked") public T fromJson(String json, Class classOfT) throws JsonParseException { - T target = (T) fromJson(json, (Type) classOfT); - return target; + Class wrapped = Primitives.wrap(classOfT); + Object object = fromJson(json, (Type) wrapped); + return wrapped.cast(object); } /** @@ -442,8 +443,9 @@ public final class Gson { * @since 1.2 */ public T fromJson(Reader json, Class classOfT) throws JsonParseException { - T target = classOfT.cast(fromJson(new JsonReader(json), classOfT)); - return target; + Class wrapped = Primitives.wrap(classOfT); + Object object = fromJson(new JsonReader(json), wrapped); + return wrapped.cast(object); } /** @@ -501,8 +503,9 @@ public final class Gson { * @since 1.3 */ public T fromJson(JsonElement json, Class classOfT) throws JsonParseException { - T target = classOfT.cast(fromJson(json, (Type) classOfT)); - return target; + Class wrapped = Primitives.wrap(classOfT); + Object object = fromJson(json, (Type) wrapped); + return wrapped.cast(object); } /** diff --git a/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java b/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java index 0be3d550..9b69bdb3 100644 --- a/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java +++ b/gson/src/test/java/com/google/gson/functional/PrimitiveTest.java @@ -16,15 +16,13 @@ package com.google.gson.functional; +import java.io.StringReader; import java.math.BigDecimal; import java.math.BigInteger; +import com.google.gson.*; import junit.framework.TestCase; -import com.google.gson.Gson; -import com.google.gson.GsonBuilder; -import com.google.gson.JsonParseException; -import com.google.gson.LongSerializationPolicy; import com.google.gson.common.TestTypes.CrazyLongTypeAdapter; /** @@ -578,4 +576,10 @@ public class PrimitiveTest extends TestCase { private static class ClassWithIntegerField { Integer i; } + + public void testPrimitiveClassLiteral() { + assertEquals(1, gson.fromJson("1", int.class).intValue()); + assertEquals(1, gson.fromJson(new StringReader("1"), int.class).intValue()); + assertEquals(1, gson.fromJson(new JsonPrimitive(1), int.class).intValue()); + } }