有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

jsonObj的java返回null。获取字符串(“键”);

 JSONObject jsonObj  = {"a":"1","b":null}
  1. 案例1:jsonObj.getString("a") returns "1";

  2. 案例2:jsonObj.getString("b") return nothing ;

  3. 案例3:jsonObj.getString("c") throws error;

如何使案例2和案例3返回null而不是"null"


共 (2) 个答案

  1. # 1 楼答案

    您可以使用get()而不是getString()。这样就返回了一个Object,JSONObject将猜测正确的类型。甚至适用于null。 请注意,Java nullorg.json.JSONObject$Null之间存在差异

    案例3不返回“nothing”,它抛出一个异常。因此,您必须检查密钥是否存在(has(key)),并返回null

    public static Object tryToGet(JSONObject jsonObj, String key) {
        if (jsonObj.has(key))
            return jsonObj.opt(key);
        return null;
    }
    

    编辑

    正如您所评论的,您只需要一个Stringnull,这将导致用于获取的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)); 
        }
    }
    
  2. # 2 楼答案

    您可以使用optString("c")optString("c", null)

    the documentation所述