Skip to content

Commit

Permalink
Merge pull request #44 from figo-connect/bigdecimal_parsing_fix
Browse files Browse the repository at this point in the history
fixed GsonAdapter to return null on NumberFormatException, added Test
  • Loading branch information
berend authored Sep 8, 2017
2 parents e9f91fa + 8c76ccd commit 970b28f
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 1 deletion.
21 changes: 20 additions & 1 deletion src/main/java/me/figo/internal/GsonAdapter.java
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Expand Down Expand Up @@ -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<BigDecimal> bigDecimalDeserializer = new JsonDeserializer<BigDecimal>() {
@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();
}
}
21 changes: 21 additions & 0 deletions src/test/java/me/figo/GsonTest.java
Original file line number Diff line number Diff line change
@@ -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");
}
}

0 comments on commit 970b28f

Please sign in to comment.