开发者

Exception while reading from JSON

开发者 https://www.devze.com 2023-04-06 02:02 出处:网络
I have this code JSONObject obj; try { obj = new JSONObject(readUrl(\"http://dleel.ps/ss.txt\")); List<String> list = new ArrayList<String>();

I have this code

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.print开发者_JAVA技巧ln(array.getJSONObject(i).getString("link"));
    }
}

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


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

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


To test if a key exists use,

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

精彩评论

暂无评论...
验证码 换一张
取 消