1

Forgive me if this is too broad a question, shout at me if so.

I'm retrieving data from a rest API in java. I then want to be able to search through the JSON data for a particular key-value pair. As far as I'm aware, a JSONObject from org.json is a good way of doing this. So far I have:

URL url = new URL("api string");
HttpURLConnection connnection = (HttpURLConnection)url.openConnection();

BufferedReader br = new BufferedReader(new InputStreamReader(connection.getInputStream()));

String input;
StringBuffer sb = new StringBuffer();

while ((input = br.readLine()) != null){
    sb.append(input);
}
br.close();

returnedJSON = new JSONObject(sb.toString());

So fairly standard get request code.

Firstly, I can't tell if I need a JSONObject or JSONArray. Everything I've researched uses JSONObjects for writing to from an API, but I'll be retrieving JSON that is in the following form:

[ { x:y, a:b, foo:bar }, { x:y, a:b, foo:bar }, ... , ... ]

So there's multiple JSON "entries" if that makes sense, and I'd like to look through the entire JSON string to see if two pieces of data exist in the same record. Ex: Is the value of 'foo' the expected value for the record where the value of 'x' is 'y'?

I'm unclear on how to proceed here as it is the first time I've properly used JSON.

3
  • If you know what kind of JSON response you are getting, which in your case is JSONArray then instantiate JSONArray instead of JSONObject Commented Apr 18, 2019 at 17:59
  • Thankyou! Does the rest of the code still make sense in the context of a JSONArray now then? Commented Apr 18, 2019 at 18:09
  • yeah, the way you arrive at your JSONArray or JSONObject remain the same. Once you get to your specific format, then you parse the response your way. Commented Apr 18, 2019 at 18:14

1 Answer 1

1

First of all you should use JSONArray instead of JSONObject because it's a array of object that you receive from API Response..

Now iterate this array and grab each of the JSONObject , which actually received in a form of HashMap (key-value pair).

Now you can get each element of JSONObject by accessing their keys..

Sign up to request clarification or add additional context in comments.

1 Comment

So now that I've used JSONArray instead of obj, my understanding is that I now just iterate through the array with a loop while searching for the specified value?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.