Json   发布时间:2022-04-22  发布网站:大佬教程  code.js-code.com
大佬教程收集整理的这篇文章主要介绍了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

大佬总结

以上是大佬教程为你收集整理的JSONObject构造时候不仅仅会抛出JSONException全部内容,希望文章能够帮你解决JSONObject构造时候不仅仅会抛出JSONException所遇到的程序开发问题。

如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。

本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。