为jsonObj.getString("key")返回null; [英] return null for jsonObj.getString("key");
问题描述
JSONObject jsonObj = {"a":"1","b":null}
-
案例1:
jsonObj.getString("a") returns "1";
案例2:jsonObj.getString("b") return nothing ;
案例3:jsonObj.getString("c") throws error;
如何使案例2和3返回null
而不是"null"
?
How to make case 2 and 3 return null
and not "null"
?
推荐答案
您可以使用get()
代替getString()
.这样,将返回Object
,并且JSONObject将猜测正确的类型.甚至对null
也适用.
请注意,Java null
和org.json.JSONObject$Null
之间是有区别的.
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
.
情况3不返回"nothing",而是引发异常.因此,您必须检查密钥是否存在(has(key)
)并返回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.
public static Object tryToGet(JSONObject jsonObj, String key) {
if (jsonObj.has(key))
return jsonObj.opt(key);
return null;
}
编辑
正如您所评论的,您只需要一个String
或null
,这会导致optString(key, default)
进行提取.查看修改后的代码:
As you commented, you only want a String
or null
, which leads to optString(key, default)
for fetching. See the modified code:
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));
}
}
这篇关于为jsonObj.getString("key")返回null;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!