java 为 jsonObj.getString("key") 返回 null;

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41778623/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 06:08:58  来源:igfitidea点击:

return null for jsonObj.getString("key");

javajson

提问by Faiyaz Md Abdul

 JSONObject jsonObj  = {"a":"1","b":null}
  1. CASE 1 : jsonObj.getString("a") returns "1";

  2. CASE 2 : jsonObj.getString("b") return nothing ;

  3. CASE 3 : jsonObj.getString("c") throws error;

  1. 情况1 : jsonObj.getString("a") returns "1";

  2. 案例2: jsonObj.getString("b") return nothing ;

  3. 案例3: jsonObj.getString("c") throws error;

How to make case 2 and 3 return nulland not "null"?

如何使案例 2 和案例 3 返回null而不返回"null"

回答by ppasler

You can use get()instead of getString(). This way an Objectis returned and JSONObject will guess the right type. Works even for null. Note that there is a difference between Java nulland org.json.JSONObject$Null.

您可以使用get()代替getString(). 这样Object返回an并且 JSONObject 将猜测正确的类型。甚至适用于null. 请注意,Javanullorg.json.JSONObject$Null.

CASE 3 does not return "nothing", it throws an Exception. So you have to check for the key to exist (has(key)) and return null instead.

CASE 3 不返回“nothing”,它抛出一个异常。因此,您必须检查键是否存在 ( has(key)) 并返回 null。

public static Object tryToGet(JSONObject jsonObj, String key) {
    if (jsonObj.has(key))
        return jsonObj.opt(key);
    return null;
}

EDIT

编辑

As you commented, you only want a Stringor null, which leads to optString(key, default)for fetching. See the modified code:

正如您所评论的,您只需要一个Stringor null,这会导致optString(key, default)获取。查看修改后的代码:

package test;

import org.json.JSONObject;

public class Test {

    public static void main(String[] args) {
        // Does not work
        // JSONObject jsonObj  = {"a":"1","b":null};

        JSONObject jsonObj  = new JSONObject("{\"a\":\"1\",\"b\":null,\"d\":1}");

        printValueAndType(getOrNull(jsonObj, "a")); 
        // >>> 1 -> class java.lang.String

        printValueAndType(getOrNull(jsonObj, "b")); 
        // >>> null -> class org.json.JSONObject$Null

        printValueAndType(getOrNull(jsonObj, "d")); 
        // >>> 1 -> class java.lang.Integer

        printValueAndType(getOrNull(jsonObj, "c")); 
        // >>> null -> null
        // throws org.json.JSONException: JSONObject["c"] not found. without a check
    }

    public static Object getOrNull(JSONObject jsonObj, String key) {
        return jsonObj.optString(key, null);
    }

    public static void printValueAndType(Object obj){
        System.out.println(obj + " -> " + ((obj != null) ? obj.getClass() : null)); 
    }
}

回答by Masoud

you can use optString("c")or optString("c", null)

你可以使用optString("c")optString("c", null)

as stated in the documentation

文档所述