1
0
Fork 0
mirror of https://github.com/ethauvin/JSON-java.git synced 2025-06-17 07:50:52 -07:00

* Prevent exceptions in cases where the value is not a string.

* Don't call toString when we know it's a string, just cast
This commit is contained in:
John J. Aylward 2017-05-18 11:41:51 -04:00
parent 0c7bd725a6
commit 382f62e781

View file

@ -980,11 +980,14 @@ public class JSONObject {
|| val instanceof Short || val instanceof Byte){ || val instanceof Short || val instanceof Byte){
return new BigDecimal(((Number) val).longValue()); return new BigDecimal(((Number) val).longValue());
} }
try { if (val instanceof String) {
return new BigDecimal(val.toString()); try {
} catch (Exception e) { return new BigDecimal((String) val);
return defaultValue; } catch (Exception e) {
return defaultValue;
}
} }
return defaultValue;
} }
/** /**
@ -1016,16 +1019,19 @@ public class JSONObject {
|| val instanceof Short || val instanceof Byte){ || val instanceof Short || val instanceof Byte){
return BigInteger.valueOf(((Number) val).longValue()); return BigInteger.valueOf(((Number) val).longValue());
} }
try { if (val instanceof String) {
// the other opt functions handle implicit conversions, i.e. try {
// jo.put("double",1.1d); // the other opt functions handle implicit conversions, i.e.
// jo.optInt("double"); -- will return 1, not an error // jo.put("double",1.1d);
// this conversion to BigDecimal then to BigInteger is to maintain // jo.optInt("double"); -- will return 1, not an error
// that type cast support that may truncate the decimal. // this conversion to BigDecimal then to BigInteger is to maintain
return new BigDecimal(val.toString()).toBigInteger(); // that type cast support that may truncate the decimal.
} catch (Exception e) { return new BigDecimal((String) val).toBigInteger();
return defaultValue; } catch (Exception e) {
return defaultValue;
}
} }
return defaultValue;
} }
/** /**
@ -1147,7 +1153,7 @@ public class JSONObject {
if (val instanceof String) { if (val instanceof String) {
try { try {
return new BigDecimal(val.toString()).intValue(); return new BigDecimal((String) val).intValue();
} catch (Exception e) { } catch (Exception e) {
return defaultValue; return defaultValue;
} }
@ -1216,7 +1222,7 @@ public class JSONObject {
if (val instanceof String) { if (val instanceof String) {
try { try {
return new BigDecimal(val.toString()).longValue(); return new BigDecimal((String) val).longValue();
} catch (Exception e) { } catch (Exception e) {
return defaultValue; return defaultValue;
} }
@ -1261,7 +1267,7 @@ public class JSONObject {
if (val instanceof String) { if (val instanceof String) {
try { try {
return new BigDecimal(val.toString()); return new BigDecimal((String) val);
} catch (Exception e) { } catch (Exception e) {
return defaultValue; return defaultValue;
} }