JSON: Checking for existence of things
in
Contributed Library Questions
•
3 months ago
If I know a certain key (?terminology) exists in a JSON object I can get it without problems:
import org.json.*;
JSON job1 = JSON.parse(playlist_rx);
JSON job2 = job1.getObject("result");
JSON job3 = job2.getArray("items");
...
but what if I don't know if job1 has got a "result"?
If I go ahead and say
JSON job2 = job1.getObject("result");
and there isn't one, an exception is thrown. So I have to code like this:
try
{
JSON job2 = job1.getObject("result");
}
catch (Exception E)
{
Oh, it doesn't have a "result", it must be one of the other sorts
}
which degenerates into a horrible mess becasue I'm expecting 3 or 4 different JSON responses.
Is there any way of checking this sort of thing without throwing exceptions?
import org.json.*;
JSON job1 = JSON.parse(playlist_rx);
JSON job2 = job1.getObject("result");
JSON job3 = job2.getArray("items");
...
but what if I don't know if job1 has got a "result"?
If I go ahead and say
JSON job2 = job1.getObject("result");
and there isn't one, an exception is thrown. So I have to code like this:
try
{
JSON job2 = job1.getObject("result");
}
catch (Exception E)
{
Oh, it doesn't have a "result", it must be one of the other sorts
}
which degenerates into a horrible mess becasue I'm expecting 3 or 4 different JSON responses.
Is there any way of checking this sort of thing without throwing exceptions?
1