From 8c76ccd0a576d1b78ac6c824328f00db0179126f Mon Sep 17 00:00:00 2001 From: Daniel Date: Fri, 8 Sep 2017 14:04:19 +0200 Subject: [PATCH] fixed GsonAdapter to return null on NumberFormatException, added Test --- .../java/me/figo/internal/GsonAdapter.java | 21 ++++++++++++++++++- src/test/java/me/figo/GsonTest.java | 21 +++++++++++++++++++ 2 files changed, 41 insertions(+), 1 deletion(-) create mode 100644 src/test/java/me/figo/GsonTest.java diff --git a/src/main/java/me/figo/internal/GsonAdapter.java b/src/main/java/me/figo/internal/GsonAdapter.java index 3b431cb..4d32f9c 100644 --- a/src/main/java/me/figo/internal/GsonAdapter.java +++ b/src/main/java/me/figo/internal/GsonAdapter.java @@ -23,6 +23,7 @@ package me.figo.internal; import java.lang.reflect.Type; +import java.math.BigDecimal; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; @@ -65,6 +66,24 @@ public Date deserialize(JsonElement json, Type type, JsonDeserializationContext } }; - return new GsonBuilder().registerTypeAdapter(Date.class, serializer).registerTypeAdapter(Date.class, deserializer).excludeFieldsWithoutExposeAnnotation().create(); + JsonDeserializer bigDecimalDeserializer = new JsonDeserializer() { + @Override + public BigDecimal deserialize(JsonElement json, Type type, JsonDeserializationContext context) + throws JsonParseException { + if (json == null) + return null; + + try { + return new BigDecimal(json.getAsString()); + } catch (NumberFormatException nfe) { + return null; + } + } + }; + + return new GsonBuilder().registerTypeAdapter(Date.class, serializer) + .registerTypeAdapter(Date.class, deserializer) + .registerTypeAdapter(BigDecimal.class, bigDecimalDeserializer).excludeFieldsWithoutExposeAnnotation() + .create(); } } diff --git a/src/test/java/me/figo/GsonTest.java b/src/test/java/me/figo/GsonTest.java new file mode 100644 index 0000000..9736d1a --- /dev/null +++ b/src/test/java/me/figo/GsonTest.java @@ -0,0 +1,21 @@ +package me.figo; + +import org.junit.Assert; +import org.junit.Test; + +import com.google.gson.Gson; + +import me.figo.models.AdditionalTransactionInfo; + +public class GsonTest { + + @Test + public void testGson() { + FigoApi api = new FigoApi("", 0); + Gson g = api.createGson(); + AdditionalTransactionInfo obj = g.fromJson( + "{\"compensation_amount\": \"6,10\",\"original_amount\": \"575.40\"}", AdditionalTransactionInfo.class); + Assert.assertNull(obj.getCompensation_amount()); + Assert.assertEquals(obj.getOriginal_amount().toPlainString(), "575.40"); + } +}