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
return null for jsonObj.getString("key");
提问by Faiyaz Md Abdul
JSONObject jsonObj = {"a":"1","b":null}
CASE 1 :
jsonObj.getString("a") returns "1";
CASE 2 :
jsonObj.getString("b") return nothing ;
CASE 3 :
jsonObj.getString("c") throws error;
情况1 :
jsonObj.getString("a") returns "1";
案例2:
jsonObj.getString("b") return nothing ;
案例3:
jsonObj.getString("c") throws error;
How to make case 2 and 3 return null
and not "null"
?
如何使案例 2 和案例 3 返回null
而不返回"null"
?
回答by ppasler
You can use get()
instead of getString()
. This way an Object
is returned and JSONObject will guess the right type. Works even for null
.
Note that there is a difference between Java null
and org.json.JSONObject$Null
.
您可以使用get()
代替getString()
. 这样Object
返回an并且 JSONObject 将猜测正确的类型。甚至适用于null
. 请注意,Javanull
和org.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 String
or null
, which leads to optString(key, default)
for fetching. See the modified code:
正如您所评论的,您只需要一个String
or 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