Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Exception while reading from JSON

Tags:

java

json

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.println(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

like image 874
Peril Avatar asked Sep 19 '11 14:09

Peril


2 Answers

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

if (array.getJSONObject(i).has("link"))
like image 164
Suraj Chandran Avatar answered Sep 26 '22 02:09

Suraj Chandran


To test if a key exists use,

array.getJSONObject(i).has("link")
like image 22
Andrew Avatar answered Sep 26 '22 02:09

Andrew