1 correct string check for JSONObject optBigDecimal and optBigInteger · W3SS/JSON-java@a7f8ff2 · GitHub
Skip to content

Commit a7f8ff2

Browse files
author
John J. Aylward
committed
correct string check for JSONObject optBigDecimal and optBigInteger
1 parent 1ab5260 commit a7f8ff2

1 file changed

Lines changed: 15 additions & 19 deletions

File tree

JSONObject.java

Lines changed: 15 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -1024,14 +1024,12 @@ public BigDecimal optBigDecimal(String key, BigDecimal defaultValue) {
10241024
|| val instanceof Short || val instanceof Byte){
10251025
return new BigDecimal(((Number) val).longValue());
10261026
}
1027-
if (val instanceof String) {
1028-
try {
1029-
return new BigDecimal((String) val);
1030-
} catch (Exception e) {
1031-
return defaultValue;
1032-
}
1027+
// don't check if it's a string in case of unchecked Number subclasses
1028+
try {
1029+
return new BigDecimal(val.toString());
1030+
} catch (Exception e) {
1031+
return defaultValue;
10331032
}
1034-
return defaultValue;
10351033
}
10361034

10371035
/**
@@ -1063,19 +1061,17 @@ public BigInteger optBigInteger(String key, BigInteger defaultValue) {
10631061
|| val instanceof Short || val instanceof Byte){
10641062
return BigInteger.valueOf(((Number) val).longValue());
10651063
}
1066-
if (val instanceof String) {
1067-
try {
1068-
// the other opt functions handle implicit conversions, i.e.
1069-
// jo.put("double",1.1d);
1070-
// jo.optInt("double"); -- will return 1, not an error
1071-
// this conversion to BigDecimal then to BigInteger is to maintain
1072-
// that type cast support that may truncate the decimal.
1073-
return new BigDecimal((String) val).toBigInteger();
1074-
} catch (Exception e) {
1075-
return defaultValue;
1076-
}
1064+
// don't check if it's a string in case of unchecked Number subclasses
1065+
try {
1066+
// the other opt functions handle implicit conversions, i.e.
1067+
// jo.put("double",1.1d);
1068+
// jo.optInt("double"); -- will return 1, not an error
1069+
// this conversion to BigDecimal then to BigInteger is to maintain
1070+
// that type cast support that may truncate the decimal.
1071+
return new BigDecimal(val.toString()).toBigInteger();
1072+
} catch (Exception e) {
1073+
return defaultValue;
10771074
}
1078-
return defaultValue;
10791075
}
10801076

10811077
/**

0 commit comments

Comments
 (0)