From a7f8ff24df65578ae966d4d12d92218bb3909984 Mon Sep 17 00:00:00 2001 From: "John J. Aylward" Date: Thu, 18 May 2017 14:41:42 -0400 Subject: [PATCH] correct string check for JSONObject optBigDecimal and optBigInteger --- JSONObject.java | 34 +++++++++++++++------------------- 1 file changed, 15 insertions(+), 19 deletions(-) diff --git a/JSONObject.java b/JSONObject.java index bba5779..d835438 100644 --- a/JSONObject.java +++ b/JSONObject.java @@ -1024,14 +1024,12 @@ public class JSONObject { || val instanceof Short || val instanceof Byte){ return new BigDecimal(((Number) val).longValue()); } - if (val instanceof String) { - try { - return new BigDecimal((String) val); - } catch (Exception e) { - return defaultValue; - } + // don't check if it's a string in case of unchecked Number subclasses + try { + return new BigDecimal(val.toString()); + } catch (Exception e) { + return defaultValue; } - return defaultValue; } /** @@ -1063,19 +1061,17 @@ public class JSONObject { || val instanceof Short || val instanceof Byte){ return BigInteger.valueOf(((Number) val).longValue()); } - if (val instanceof String) { - try { - // the other opt functions handle implicit conversions, i.e. - // jo.put("double",1.1d); - // jo.optInt("double"); -- will return 1, not an error - // this conversion to BigDecimal then to BigInteger is to maintain - // that type cast support that may truncate the decimal. - return new BigDecimal((String) val).toBigInteger(); - } catch (Exception e) { - return defaultValue; - } + // don't check if it's a string in case of unchecked Number subclasses + try { + // the other opt functions handle implicit conversions, i.e. + // jo.put("double",1.1d); + // jo.optInt("double"); -- will return 1, not an error + // this conversion to BigDecimal then to BigInteger is to maintain + // that type cast support that may truncate the decimal. + return new BigDecimal(val.toString()).toBigInteger(); + } catch (Exception e) { + return defaultValue; } - return defaultValue; } /**