6

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

Brian Roach
  • 76,169
  • 12
  • 136
  • 161
Peril
  • 1,569
  • 6
  • 25
  • 42
  • What exception? Please post the stack trace. – Brian Roach Sep 19 '11 at 14:47
  • you can see the JSON file in the txt shown in the readUrl function – Peril Sep 19 '11 at 14:48
  • @Brain Roach java.util.NoSuchElementException: JSONObject["link"] not found. it reads the first one , but it fails to read the second one because its null – Peril Sep 19 '11 at 14:49
  • 1
    @Salah: There's a *lot* of JSON there. Please do the work to find which bit of it is causing a problem, and also show us the exception you're having trouble with. Read http://tinyurl.com/so-hints for suggestions about how to write a good question. – Jon Skeet Sep 19 '11 at 14:50

2 Answers2

16

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

if (array.getJSONObject(i).has("link"))
Suraj Chandran
  • 24,433
  • 12
  • 63
  • 94
  • 2
    u might wanna accept it as the right answer, so it might help others with same problem :) – Suraj Chandran Sep 19 '11 at 14:51
  • 4
    You can also use the .optString("link") method, which returns null if the string doesn't exist instead of throwing an exception. – lucasmo Sep 19 '11 at 17:00
  • @SurajChandran just a quick question , how can compare the getJSONObject(i).getString("link") with another string ? – Peril Sep 19 '11 at 21:07
2

To test if a key exists use,

array.getJSONObject(i).has("link")
Andrew
  • 13,757
  • 13
  • 66
  • 84