为jsonObj.getString("key")返回null; [英] return null for jsonObj.getString("key");

查看:280
本文介绍了为jsonObj.getString("key")返回null;的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 JSONObject jsonObj  = {"a":"1","b":null}

  1. 案例1:jsonObj.getString("a") returns "1";

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

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

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

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

推荐答案

您可以使用get()代替getString().这样,将返回Object,并且JSONObject将猜测正确的类型.甚至对null也适用. 请注意,Java nullorg.json.JSONObject$Null之间是有区别的.

You can use get() instead of getString(). This way an Object is returned and JSONObject will guess the right type. Works even for null. Note that there is a difference between Java null and org.json.JSONObject$Null.

情况3不返回"nothing",而是引发异常.因此,您必须检查密钥是否存在(has(key))并返回null.

CASE 3 does not return "nothing", it throws an Exception. So you have to check for the key to exist (has(key)) and return null instead.

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

编辑

正如您所评论的,您只需要一个Stringnull,这会导致optString(key, default)进行提取.查看修改后的代码:

As you commented, you only want a String or null, which leads to optString(key, default) for fetching. See the modified code:

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)); 
    }
}

这篇关于为jsonObj.getString("key")返回null;的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆