大佬教程收集整理的这篇文章主要介绍了JSONObject构造时候不仅仅会抛出JSONException,大佬教程大佬觉得挺不错的,现在分享给大家,也给大家做个参考。
如下列代码:
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; }
/** The input JSON. */ private final String in;
下面是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"); } }
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(); } }
private int nextCleanInternal() throws JSONException { while (pos < in.length()) { int c = in.charAt(pos++); switch (C) { case '\t': case ' ': case '\n': case '\r': conTinue; //由于方法体过长,省略一下
所以在使用字符串构造JSONObject时,建议先检测一下字符串是否为null
以上是大佬教程为你收集整理的JSONObject构造时候不仅仅会抛出JSONException全部内容,希望文章能够帮你解决JSONObject构造时候不仅仅会抛出JSONException所遇到的程序开发问题。
如果觉得大佬教程网站内容还不错,欢迎将大佬教程推荐给程序员好友。
本图文内容来源于网友网络收集整理提供,作为学习参考使用,版权属于原作者。
如您有任何意见或建议可联系处理。小编QQ:384754419,请注明来意。