zoukankan      html  css  js  c++  java
  • JSON中getInt()和optInt()的区别

           最近在用org.json这个包解析json的时候,发现谷歌提供两种不同的数据类型获取方法,比如说针对Int类型,提供了getInt()和optInt()两种方式,谷歌文档中的说明如下:

    这里写图片描述

    这里写图片描述

    那么这两者有什么区别呢?我们来看下源码:

    public int getInt(String key) throws JSONException {  
        Object object = this.get(key);  
        try {  
            return object instanceof Number ? ((Number) object).intValue()  
                    : Integer.parseInt((String) object);  
        } catch (Exception e) {  
            throw new JSONException("JSONObject[" + quote(key)  
                    + "] is not an int.");  
        }  
    }  
    public int optInt(String key) {  
        return this.optInt(key, 0);  
    }  

    不难发现,二者区别如下:

    getInt()取值不正确或者类型不正确时会抛出异常,必须用try catch或者throw捕获

    optInt()取值不正确时则会试图进行转化或者返回默认值,不会抛出异常

    安卓开发高级技术交流QQ群:108721298 欢迎入群

    微信公众号:mobilesafehome

    (本公众号支持投票)

    Android安全技术大本营

  • 相关阅读:
    117. Populating Next Right Pointers in Each Node II
    50. Pow(x, n)
    494. Target Sum
    Word Ladder
    HDU 4417
    POJ 2104
    POJ 3277
    【转】图论500题
    POJ 2991
    POJ 1436
  • 原文地址:https://www.cnblogs.com/itrena/p/5938212.html
Copyright © 2011-2022 走看看