JSONObject構造時候不僅僅會拋出JSONException

來源:互聯網
上載者:User

一開始認為在構造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


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.