Json解析时,一系列opt***方法

    xiaoxiao2021-03-25  104

    做西邮图书馆的时候,需要使用json解析, 使用jsonObject和jsonArray来解析服务端返回的json数据在jsonObject获取value有多种方法,如果key不存在的话,这些方法无一例外的都会抛出异常。如果在线环境抛出异常,就会使出现error页面,影响用户体验,针对这种情况最好是使用optXXX方法。

    在解析的时候学长说最好使用 JSONObject.optString("key")

    JSONObject有很多optXXX方法,比如optBoolean,optString,optInt。它们的意思是,如果JsonObject有这个属性,则返回这个属性,否则返回一个默认值。

    点进去跟了一下源码

    public int optInt(String name) { return optInt(name, 0); } /** * Returns the value mapped by {@code name} if it exists and is an int or * can be coerced to an int, or {@code fallback} otherwise. */ public int optInt(String name, int fallback) { Object object = opt(name); Integer result = JSON.toInteger(object); return result != null ? result : fallback;//一目了然 }

    记录下,以后最好使用这种opt方法

    转载请注明原文地址: https://ju.6miu.com/read-23117.html

    最新回复(0)