android解析JSON数据

2019-12-10 18:41:46王旭

JsonObject的解析过程

一、 JsonObject还有一个带参数的构造函数:常用的是传递一个String类型的参数

public JSONObject(String json) throws JSONException {
  this(new JSONTokener(json));
}

二、 跟进去,发现主要执行的是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();
  }
}

在nextCleanInternal方法中,它会从头到尾的逐个字符的解析,对于一些字符做一些处理。例如空格,换行,转义符等!
当解析到[表示开始一个对象的读取,当解析到{表示一个数组的读取

三、 在readObject方法中,仍然是调用nextCleanInternal()方法,逐个得到解析的字符,下到解析到}.下面贴出重要代码

int first = nextCleanInternal(); // 得到解析的字符
if (first == '}') {
  return result;
} else if (first != -1) {
  pos--;
}
.......
while (true) {
  Object name = nextValue(); // 解析得到键
  
  int separator = nextCleanInternal();
  if (separator != ':' && separator != '=') {
    throw syntaxError("Expected ':' after " + name);
  }
  if (pos < in.length() && in.charAt(pos) == '>') {
    pos++;
  }

  result.put((String) name, nextValue()); // 将解析得到的键值对,存放在map当中

  switch (nextCleanInternal()) {
    case '}':
      return result;
    case ';':
    case ',':
      continue;
    default:
      throw syntaxError("Unterminated object");
  }
}