所以我在scala中解析JSON。我有一个偶尔为空的物体。我该怎么处理这个?
我认为if (json.get("object") != null) {...}
会起作用,但事实并非如此。
这是我一直在尝试的代码:
import org.json._
val json: JSONObject = new JSONObject("{\"object\": null}")
if (json.get("object") != null) {
println("The object is not null") //This like is executed
} else {
println("the object is null") This line is not executed
}
println(json.getString("object")) //This line returns "org.json.JSONException: JSONObject["object"] not a string."
那么在解析JSON时如何避免空指针异常?
答案 0 :(得分:0)
用于初始化,请使用JSONObject.NULL
而不是null
要检查null
值,请使用public boolean isNull(java.lang.String key)