Java Gamer
Java Gamer

Reputation: 577

Looping through json and picking random objects by id - Android/JAVA

So I have a json file, which has about 350 objects. I have provided a sample of how it looks below:

"type": "success",
  "value": [
    {
      "id": 1,
      "joke": "Joke 1 - Text",
      "categories": [
        "explicit"
      ]
    },
    {
      "id": 2,
      "joke": "Joke 2 - Text.",
      "categories": [

      ]
    },
    {
      "id": 3,
      "joke": "Joke 3 - Text",
      "categories": [

      ]
    },

So far I have been able get the first joke, but I used a json which only had one joke. Now I want to loop through everything and get 2 random joke. I have seen examples where people used json array to loop, but it didn't work for me because my json file structure is different. So this is how I got the first object:

String finalJson = buffer.toString();

            JSONObject parentObject = new JSONObject((finalJson));

            JSONObject finalObj = parentObject.getJSONObject("value");


            String jokes = finalObj.getString("joke");
            int id = finalObj.getInt("id");


            return id + " " + jokes;

Like I said before I want to loop through each object then pick 2 random id's and get the joke. I dont know if this is the best way to do it, But my idea is to have a Random r which has a max value of 350 and min of 1 then pick the joke object by id according to the random nr.

Upvotes: 0

Views: 1089

Answers (1)

Terry W
Terry W

Reputation: 203

value is not a JSONObject, but a JSONArray, this should give you two random jokes

String finalJson = buffer.toString();

JSONObject parentObject = new JSONObject((finalJson));

//JSONObject finalObj = parentObject.getJSONObject("value");
JSONArray jokeArray = parentObject.getJSONArray("value");

Random r = new Random();
String joke1 = jokeArray.getJSONObject(r.nextInt(jokeArray.length())).getString("joke");
String joke2 = jokeArray.getJSONObject(r.nextInt(jokeArray.length())).getString("joke");

This also depends on the fact the ids will always start at 1 and increment 1 at a time

EDIT

To display the ID too, break it down further...

String finalJson = buffer.toString();

JSONObject parentObject = new JSONObject((finalJson));

//JSONObject finalObj = parentObject.getJSONObject("value");
JSONArray jokeArray = parentObject.getJSONArray("value");

Random r = new Random();
int id1 = r.nextInt(jokeArray.length())
String joke1 = jokeArray.getJSONObject(id1).getString("joke");

int id2 = r.nextInt(jokeArray.length())
String joke2 = jokeArray.getJSONObject(id1).getString("joke");

String joke1WithID = id1 + "  " + joke1
String joke2WithID = id2 + "  " + joke2

Upvotes: 1

Related Questions