Return null for jsonObj.getString ("key");

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

  • CASE 2: jsonObj.getString("b") return nothing ;

  • CASE 3: jsonObj.getString("c") throws error;

How to make case 2 and 3 return null, not "null"?

+4
source share
1 answer

You can use get()instead getString(). Thus it returns Object, and JSONObject guesses the correct type. It even works for null. Please note that there is a difference between Java nulland org.json.JSONObject$Null.

CASE 3 does not return "nothing", it throws an exception. So you need to check if the key ( has(key)) exists and return null instead.

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

EDIT

, 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)); 
    }
}
+6

Source: https://habr.com/ru/post/1667424/


All Articles