且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在JSON对象中存在或不存在检查值以避免JSON异常

更新时间:2023-11-29 09:51:40

有一种方法 JSONObject#has(key) 就是为了这个目的。这样就可以避免每个字段的异常处理。

There is a method JSONObject#has(key) meant for exactly this purpose. This way you can avoid the exception handling for each field.

if(result.has("fieldName")){
    // It exists, do your stuff
} else {
    // It doesn't exist, do nothing 
}

此外,您可以使用 JSONObject#isNull(str) 方法检查它是否为 null 或不。

Also, you can use the JSONObject#isNull(str) method to check if it is null or not.

if(result.isNull("fieldName")){
    // It doesn't exist, do nothing
} else {
    // It exists, do your stuff
}

您还可以将其移动到一个方法(用于代码重用),在该方法中传递JSONObject和String,如果字段存在与否,则返回该方法。

You can also move this to a method(for code re-use), where you pass a JSONObject and a String and the method returns if the field is present or not it.