1

En este json, me gustaría conseguir sacar de results, del id PC todos los games: https://api.rawg.io/api/platforms?key=bf61e2970a4d4af8b77dac08fbc273f4

{
   "count":51,
   "next":"https://api.rawg.io/api/platforms?key=bf61e2970a4d4af8b77dac08fbc273f4&page=2",
   "previous":null,
   "results":[
      {
         "id":4,
         "name":"PC",
         "slug":"pc",
         "games_count":446263,
         "image_background":"https://media.rawg.io/media/games/588/588c6bdff3d4baf66ec36b1c05b793bf.jpg",
         "image":null,
         "year_start":null,
         "year_end":null,
         "games":[
            {
               "id":3498,
               "slug":"grand-theft-auto-v",
               "name":"Grand Theft Auto V",
               "added":17407
            },
            {
               "id":3328,
               "slug":"the-witcher-3-wild-hunt",
               "name":"The Witcher 3: Wild Hunt",
               "added":16143
            },
            {
               "id":4200,
               "slug":"portal-2",
               "name":"Portal 2",
               "added":15229
            },
            {
               "id":5286,
               "slug":"tomb-raider",
               "name":"Tomb Raider (2013)",
               "added":13629
            },
            {
               "id":5679,
               "slug":"the-elder-scrolls-v-skyrim",
               "name":"The Elder Scrolls V: Skyrim",
               "added":13210
            },
            {
               "id":4291,
               "slug":"counter-strike-global-offensive",
               "name":"Counter-Strike: Global Offensive",
               "added":13119
            }
         ]
      }
  }

EDIT(Este seria el codigo que estoy intentando utilizar, pero me da error en el JSONObject["object"]):

JSONObject json = readJsonFromUrl("https://api.rawg.io/api/platforms?key=bf61e2970a4d4af8b77dac08fbc273f4"); 

        JSONObject jsonobject1 = json.getJSONObject("object");
//      JSONObject jsresults = jsonobject.getJSONObject("results");
//      JSONObject js0 = jsresults.getJSONObject("0");
//      JSONObject jsgames = js0.getJSONObject("games");
//      System.out.println(jsgames.get("name"));

        JSONArray arr = jsonobject1.getJSONArray("results");
        for (int i = 0; i < arr.length(); i++) {
            String post_id = arr.getJSONObject(i).getString("0");
            System.out.println(post_id);
        }

3
  • y como lo has intentado, muestranos tu codigo para poder ayudarte....
    – David081
    el 31 may. 2022 a las 17:29
  • Publica en la pregunta el fragmento de código al que te refieres y un poco de contexto, así como la salida esperada.
    – Pepe N O
    el 31 may. 2022 a las 17:32
  • Acabo de poner el código que estoy utilizando
    – jolugara
    el 31 may. 2022 a las 17:36

2 respuestas 2

0

Para obtener el nombre de los games:

JSONObject json = readJsonFromUrl("https://api.rawg.io/api/platforms?key=bf61e2970a4d4af8b77dac08fbc273f4");        
        //convert json results to array
        JSONArray jsonArray = json.getJSONArray("results");
        //from jsonArray name PC get games names
        JSONObject jsonObject = jsonArray.getJSONObject(0);
        //get games names
        JSONArray jsonArray2 = jsonObject.getJSONArray("games");
        //iterate over jsonArray2 and print names
        for (int i = 0; i < jsonArray2.length(); i++) {
            System.out.println(jsonArray2.getJSONObject(i).getString("name"));
        }        

Para ver las consolas y sus juegos:

JSONObject json = readJsonFromUrl("https://api.rawg.io/api/platforms?key=bf61e2970a4d4af8b77dac08fbc273f4");        
        //convert json results to array
        JSONArray jsonArray = json.getJSONArray("results");
        //iterate over array
        for (int i = 0; i < jsonArray.length(); i++) {
            System.out.println(jsonArray.getJSONObject(i).get("name"));
            JSONObject jsonObject = jsonArray.getJSONObject(i);    
            JSONArray jsonArray2 = jsonObject.getJSONArray("games");
            //iterate over jsonArray2 and print names
            for (int j = 0; j < jsonArray2.length(); j++) {
                System.out.println("---"+jsonArray2.getJSONObject(j).getString("name"));
            }        
        }
3
  • Vale, otra cosita, si quisiera que saliera el name y también la consola a la que pertenece cada juego, en este caso PC, ¿Cómo podría hacer para que aparecieran ambos datos?
    – jolugara
    el 31 may. 2022 a las 18:22
  • Vale, al final lo conseguí, era simplemente añadir dentro del for lo siguiente: System.out.println(jsonObject.getString("name"));
    – jolugara
    el 31 may. 2022 a las 18:32
  • Hay que ver la estructura de tu JSON y sus niveles, te puse un ejemplo iterando todas las consolas y sus juegos.
    – Pepe N O
    el 31 may. 2022 a las 18:34
0

Puedes obtener los juegos de PC, de manera simple usando una combinación de getJSONArray y getJSONObject dependiendo del tipo de objeto que sea la clave en el json. Finalmente puedes iterar los juegos de PC con un simple for:

JSONArray gamesPC = json.getJSONArray( "results" )
        .getJSONObject( 0 )
        .getJSONArray( "games" );

for (int i = 0; i < gamesPC.length(); i++) {
    JSONObject game = gamesPC.getJSONObject( i );
    System.out.println(game.toString(4));
    
    // Alternativamente usa esto para imprimir solo el nombre  
    System.out.println(game.getString("name"));
}
2
  • Vale muchas gracias, y si quisiera sacar 1 solo dato de dentro de game, por ejemplo el nombre?
    – jolugara
    el 31 may. 2022 a las 18:03
  • @jolugara dentro del for después de game simplemente usas String name = game.getString( "name" ). Te lo agregué en el código.
    – Jaime
    el 31 may. 2022 a las 18:05

Tu Respuesta

By clicking “Publica tu respuesta”, you agree to our terms of service and acknowledge you have read our privacy policy.

¿No es la respuesta que buscas? Examina otras preguntas con la etiqueta o formula tu propia pregunta.