JSONObject #getString(String string) 空值(null)问题

前端之家收集整理的这篇文章主要介绍了JSONObject #getString(String string) 空值(null)问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

今天在android4.4.2(android-19)平台上做Json数据解析的时候碰到了这样一个问题:

返回的数据为:{"message":null}

当使用:JSONObject jsonObj = new JSONObject(jsonMessage);

String message=jsonObj.getString("message");

本以为message 是空值(null)

结果总不能如愿,最后发现:getString(),如果value是空值,那么这个方法会返回一个“null"字面量,而不是null对象。


源码:

  1. /**
  2. * Returns the value mapped by {@code name} if it exists,coercing it if
  3. * necessary.
  4. *
  5. * @throws JSONException if no such mapping exists.
  6. */
  7. public String getString(String name) throws JSONException {
  8. Object object = get(name);
  9. String result = JSON.toString(object);
  10. if (result == null) {
  11. throw JSON.typeMismatch(name,object,"String");
  12. }
  13. return result;
  14. }

猜你在找的Json相关文章