在进行单元测试时,我注意到在运行单元测试时调用 JSONObject.getNumber() 时出现一些奇怪的行为。这是错误:
java.lang.NoSuchMethodError: 'java.lang.Number org.json.JSONObject.getNumber(java.lang.String)
这是代码:
Number logId;
logId = jsonObject.getNumber("logId");
对于我自己的实现,我可以使用这个:
logId = jsonObject.getInt("logId");
但我真的很想知道在尝试使用 JSONObject.getNumber() 进行单元测试时我错过了什么。为什么缺少 getNumber() 方法?
编辑于2019-12-20 13:59
我正在使用 Maven groupID 'org.json',artifactId 'json',版本 '20190722'。我在定制的 new JSONObject().put(stuff).put(stuff)
.getNumber()
最佳答案
请检查您的 json 版本。我能够在版本中找到 jsonObject.getNumber():'20180813'
这是gradle依赖供您引用
compile group: 'org.json', name: 'json', version: '20180813'
这是在该 jar 中找到的实现类
/**
* Get the Number value associated with a key.
*
* @param key
* A key string.
* @return The numeric value.
* @throws JSONException
* if the key is not found or if the value is not a Number
* object and cannot be converted to a number.
*/
public Number getNumber(String key) throws JSONException {
Object object = this.get(key);
try {
if (object instanceof Number) {
return (Number)object;
}
return stringToNumber(object.toString());
} catch (Exception e) {
throw new JSONException("JSONObject[" + quote(key)
+ "] is not a number.", e);
}
}
关于java - 使用unittest调用时org.json.JSONObject.getNumber()抛出 "NoSuchMethodError",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59411008/