dimanche 20 mars 2016

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.




Aucun commentaire:

Enregistrer un commentaire