JSONObject jsonObj = {"a":"1","b":null}
Run Code Online (Sandbox Code Playgroud)
情况1 : jsonObj.getString("a") returns "1";
案例2: jsonObj.getString("b") return nothing ;
案例3: jsonObj.getString("c") throws error;
如何让案例2和3返回null而不是"null"?
ppa*_*ler 12
你可以用get()而不是getString().这样Object返回一个,JSONObject将猜测正确的类型.甚至可以工作null.请注意,Java null和org.json.JSONObject$Null.之间存在差异.
CASE 3不会返回"无",它会抛出异常.所以你必须检查exists(has(key))的键并返回null.
public static Object tryToGet(JSONObject jsonObj, String key) {
if (jsonObj.has(key))
return jsonObj.opt(key);
return null;
}
Run Code Online (Sandbox Code Playgroud)
编辑
正如您所评论的那样,您只需要一个String或者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));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
11002 次 |
| 最近记录: |