JSONObject构造时候不仅仅会抛出JSONException

一开始认为在构造json相关的对象时,如果传输的字符串参数为null,也会当作JSONException抛出,但是今天遇到了发现不是,会抛出一个NullPointerException,这里需要我们进行一下相关的处理。

如下列代码:

public void testJSONConstructor() {
		final String jsonStr = null;
		try {
			JSONObject jsonObj = new JSONObject(jsonStr);
		} catch (JSONException e) {
			e.printStackTrace();
		} catch (NullPointerException e) {
			e.printStackTrace();
		}
	}
然而异常被捕获为NullPointerException,而不是JSONObjectException,但是为什么呢,明明如下代码声明
  public JSONObject(String json) throws JSONException {
        this(new JSONTokener(json));
    }
对,上面的代码确实是标明了扔出JSONException,那我们看看是如何抛出这个NPE的

首先我们看JSONTokener的构造函数,带字符串参数的这个

public JSONTokener(String in) {
        // consume an optional byte order mark (BOM) if it exists
        if (in != null && in.startsWith("\ufeff")) {
            in = in.substring(1);
        }
        this.in = in;
    }

而且this.in的声明是这样的

/** The input JSON. */
    private final String in;

所以如何参数in为null,则成员属性也为null

下面是JSONObject带JSONTokener的构造函数

public JSONObject(JSONTokener readFrom) throws JSONException {
        /*
         * Getting the parser to populate this could get tricky. Instead, just
         * parse to temporary JSONObject and then steal the data from that.
         */
        Object object = readFrom.nextValue();
        if (object instanceof JSONObject) {
            this.nameValuePairs = ((JSONObject) object).nameValuePairs;
        } else {
            throw JSON.typeMismatch(object, "JSONObject");
        }
    }

那么是哪里引起的NPE呢,JSONTokener调用的nextValue方法

 public Object nextValue() throws JSONException {
        int c = nextCleanInternal();
        switch (c) {
            case -1:
                throw syntaxError("End of input");

            case '{':
                return readObject();

            case '[':
                return readArray();

            case '\'':
            case '"':
                return nextString((char) c);

            default:
                pos--;
                return readLiteral();
        }
    }

nextValue又调用的nextCleanInternal

 private int nextCleanInternal() throws JSONException {
        while (pos < in.length()) {
            int c = in.charAt(pos++);
            switch (c) {
                case '\t':
                case ' ':
                case '\n':
                case '\r':
                    continue;
  //由于方法体过长,省略一下

所以,我们看到了之前的成员属性in 由于参数为null,没有被赋值,所以还是默认的Null,所以这里就出现了NullPointerException


所以在使用字符串构造JSONObject时,建议先检测一下字符串是否为null


  • 2
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值