我的问题:如何改进这些方法来检查字符串是否有效 json ,而不必JSONException
通过使用官方 JSON for java 库来忽略 s ?
public boolean isValidJSON(String possibleJson) {
return isJSONObject(possibleJson) || isJSONArray(possibleJson);
}
private boolean isJSONObject(String possibleJson) {
try {
new JSONObject(possibleJson);
return true;
} catch (JSONException ex) {
return false;
}
}
private boolean isJSONArray(String possibleJson) {
try {
new JSONArray(possibleJson);
return true;
} catch (JSONException ex) {
return false;
}
}
我很确定依赖作为方法中逻辑的一部分抛出的异常不是最佳实践。还有另一种方法可以做到这一点吗?
注意:请记住,我不希望使用其他库来执行此操作。它只是一个大项目的一小部分,如果我能提供帮助,我不想引入另一个依赖项。