从JSON读取时出现异常 [英] Exception while reading from JSON

查看:182
本文介绍了从JSON读取时出现异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这段代码

JSONObject obj;
try {
    obj = new JSONObject(readUrl("http://dleel.ps/ss.txt"));
    List<String> list = new ArrayList<String>();
    JSONArray array = obj.getJSONArray("data");

    for(int i = 0 ; i < array.length() ; i++) {
        if (array.getJSONObject(i).getString("link")!=null)
        System.out.println(array.getJSONObject(i).getString("link"));
    }
}

为什么我没有链接时会出现异常(JSONObject找不到[link]。),我应该在if条件下放什么?
我也尝试使用而不是getJSONArray,optJSONArray但是相同的

why I am getting exception when theres no link (JSONObject["link"] not found.) , what should I put in the if condition ? also I tried using instead of getJSONArray , optJSONArray but the same

推荐答案

getString()方法如果找不到密钥则抛出异常。
而是使用 has()方法:

The getString() method throws exception if key not found. Instead use the has() method:

if (array.getJSONObject(i).has("link"))

这篇关于从JSON读取时出现异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆