jsonObj的java返回null。获取字符串(“键”);
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"
你可以在下面搜索框中键入要查询的问题!
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"
# 1 楼答案
您可以使用
get()
而不是getString()
。这样就返回了一个Object
,JSONObject将猜测正确的类型。甚至适用于null
。 请注意,Javanull
和org.json.JSONObject$Null
之间存在差异案例3不返回“nothing”,它抛出一个异常。因此,您必须检查密钥是否存在(
has(key)
),并返回null编辑
正如您所评论的,您只需要一个
String
或null
,这将导致用于获取的optString(key, default)
。请参阅修改后的代码:# 2 楼答案
您可以使用
optString("c")
或optString("c", null)
如the documentation所述