java JSON.getString 不返回 null
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13118146/
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
JSON.getString doesn't return null
提问by thepoosh
I have a response coming back from a server and I am expecting a String value, so I wrote this for parsing it
我有一个从服务器返回的响应,我期待一个字符串值,所以我写了这个来解析它
public String getMessageFromServer(JSONObject response) {
String msg = response.getString("message");
return msg;
}
then, when I use this in my code and get a null
value from the server, the function doesn't return null
, it returns "null"
instead.
然后,当我在我的代码中使用它并null
从服务器获取一个值时,该函数不会返回null
,而是返回"null"
。
I have seen this bug report, but I don't see a solution.
我看过这个错误报告,但我没有看到解决方案。
EDIT:
编辑:
I have a small hack to solve this but it's ugly and I'm looking for a better solution:
我有一个小技巧来解决这个问题,但它很难看,我正在寻找更好的解决方案:
public String getMessageFromServer(JSONObject response) {
Object msg = response.get("message");
if(msg == null) {
return null;
}
return (String) msg;
}
EDIT #2:
编辑#2:
after years, going back to this question, I see that I was not entirely wrong here and that JSONObject
has a built in method for this.
多年后,回到这个问题,我发现我在这里并没有完全错,并且JSONObject
有一个内置的方法。
The way to get an optional value from a JSONObject
is with using this methodJSONObject.optString("message", DEF_VALUE);
从 a 获取可选值的方法JSONObject
是使用此方法JSONObject.optString("message", DEF_VALUE);
回答by Sujay
The hack looks okay for your situation.
对于您的情况,hack 看起来不错。
The other option would be to use the method boolean isNull(String key)
and then based on the returned boolean value proceed with your option. Something like:
另一种选择是使用该方法boolean isNull(String key)
,然后根据返回的布尔值继续您的选择。就像是:
public String getMessageFromServer(JSONObject response) {
return ((response.has("message") && !response.isNull("message"))) ? response.getString("message") : null;
}
But then, I don't think there's much of a difference between the your current implementation and this.
但是,我认为您当前的实现与此之间没有太大区别。
回答by jhavatar
This is easy to solve when using Kotlin class extensions:
这在使用 Kotlin 类扩展时很容易解决:
fun JSONObject.optNullableString(name: String, fallback: String? = null) : String? {
return if (this.has(name) && !this.isNull(name)) {
this.getString(name)
} else {
fallback
}
}
Then e.g. name
will be null in:
然后 egname
将在以下情况下为空:
val name : String? = JSONObject("""{"id": "foo", "name":null}""").optNullableString("name")