JSON空值使用opt()



我正在研究一个API,该API通过将null值放在最初持有double/float值的一些项目上而设计不良。现在我认为必须有一个简短的解决方案,我不需要做大量的if else语句只是为了检查一个值是否为空,这似乎是通过使用optDouble("key", fallback_value)来完成的,但每当一个字段值为空时,错误仍然会发生。

异常堆栈:

W/System.err: org.json.JSONException: Value null at median_tx_value of type org.json.JSONObject$1 cannot be converted to double

我试着检查方法

的源代码
/**
* Returns the value mapped by {@code name} if it exists and is a double or
* can be coerced to a double, or {@code fallback} otherwise.
*/
public double optDouble(@Nullable String name, double fallback) {
Object object = opt(name);
Double result = JSON.toDouble(object);
return result != null ? result : fallback;
}

似乎错误开始于JSON.toDouble(object),其中对象已经为空。有没有办法在不使用第三方库的情况下实现它?

这是我目前的临时解决方案,请随时改进。

private double optionalDouble(JSONObject object, String key){
if (!object.isNull(key)) {
try {
return object.getDouble(key);
} catch (JSONException e) {
e.printStackTrace();
return 0.0;
}
}
else
return 0.0;
}