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) {
JSONObject jsonObj = new JSONObject("{\"a\":\"1\",\"b\":null,\"d\":1}");
printValueAndType(getOrNull(jsonObj, "a"));
printValueAndType(getOrNull(jsonObj, "b"));
printValueAndType(getOrNull(jsonObj, "d"));
printValueAndType(getOrNull(jsonObj, "c"));
}
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));
}
}