0

Tengo el siguiente código:

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.Iterator;
import org.json.JSONArray;
import org.json.JSONObject;

public class Test {

public static void main(String[] args) {
    try {
        Test.call_me();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public static void call_me() throws Exception {
    String url = "https://www.googleapis.com/youtube/v3/videos?id=Ald6YIXwiyI&key=AIzaSyBMHhfr4Crs6OvrV7nEnWWSF7bmRDHkgOg&part=statistics&fields=items(id,statistics)";
    URL obj = new URL(url);
    HttpURLConnection con = (HttpURLConnection) obj.openConnection();
    // optional default is GET
    con.setRequestMethod("GET");
    //add request header
    con.setRequestProperty("User-Agent", "Mozilla/5.0");
    int responseCode = con.getResponseCode();
    System.out.println("\nSending 'GET' request to URL : " + url);
    System.out.println("Response Code : " + responseCode);
    BufferedReader in = new BufferedReader(
            new InputStreamReader(con.getInputStream()));
    String inputLine;
    StringBuffer response = new StringBuffer();
    while ((inputLine = in.readLine()) != null) {
        response.append(inputLine);
    }
    in.close();
    //print in String
    //System.out.println(response.toString());
    //Read JSON response and print

    JSONObject myResponse = new JSONObject(response.toString());
    //System.out.println(response.toString());
    System.out.println(myResponse.toString());
    JSONObject items = new JSONObject(myResponse.getJSONArray("items").getJSONArray(0));

Ahora esto me genera un Json del siguiente formato:

{"items":[{"id":"Ald6YIXwiyI","statistics":     {"dislikeCount":"46","likeCount":"3483","viewCount":"43745","favoriteCount":"0","commentCount":"499"}}]}

Mi duda es como puedo guardar este Json en un ArrayList o en un una estructura de datos, revise en un editor Json online y tengo una estructura de tipo arreglo en el código intento acceder mediante un:

getJSONArray("items")

Pero solo me devuelve una posición y se encuentra en blanco

1 respuesta 1

1

te paso un ejemplo de como puedes recorrerlo,con esto podras obtener los valores y guardarlos en un ArrayList por ejemplo.

public class Parser {

/**
 * @param args the command line arguments
 */
public static void main(String[] args) {

    try {
        ///Descomponer un JSON
        String respuesta="{\"items\":[{\"id\":\"Ald6YIXwiyI\",\"statistics\":     {\"dislikeCount\":\"46\",\"likeCount\":\"3483\",\"viewCount\":\"43745\",\"favoriteCount\":\"0\",\"commentCount\":\"499\"}}]}";

        JSONParser jsonParser = new JSONParser();
        JSONObject jsonObject = (JSONObject) jsonParser.parse(respuesta);

                    ///items es un Array
                    JSONArray ArrayItems= (JSONArray) jsonObject.get("items");

                    System.err.println("ARRAY:"+ArrayItems.toJSONString());

                    ///si es un array  y solo tiene una posicion,podemos acceder con la posicion 0
                    ///statistics es un objeto 
                   JSONObject statisticsFrom =(JSONObject) ArrayItems.get(0);

                    System.err.println("CUERPO:"+statisticsFrom.toJSONString());

                    ///accedemos al objecto statistics mediante su nombre por ejemplo.

                    JSONObject jsonObjectstatistics =(JSONObject) statisticsFrom.get("statistics"); 

                    System.err.println("OBJETO:"+jsonObjectstatistics.toJSONString());
                    ///con esto ya estamos dento del objecto statistics y podemos obtener todos sus campos.
                    System.err.println("dislikeCount:"+jsonObjectstatistics.get("dislikeCount"));
                    System.err.println("likeCount:"+jsonObjectstatistics.get("likeCount"));
                    System.err.println("viewCount:"+jsonObjectstatistics.get("viewCount"));
                    System.err.println("favoriteCount:"+jsonObjectstatistics.get("favoriteCount"));
                    System.err.println("commentCount:"+jsonObjectstatistics.get("commentCount"));

                    ////todo lo anterior siempre y cuando el JSON posea un solo objeto en el Array
                    ////de otra manera se puede recorrer con un for y obtener todos los valores.

                   for(int i=0; i<ArrayItems.size(); i++){

                        JSONObject cuerpo =(JSONObject) ArrayItems.get(i);
                        JSONObject statistics =(JSONObject) cuerpo.get("statistics"); 
                        ///el id lo obtenemos aqui porque esta en el objecto cuerpo
                         String id=cuerpo.get("id").toString();

                         ////Ahora recorremos finalmente el objecto statistics
                         String dislikeCount=statistics.get("dislikeCount").toString();
                         String likeCount=statistics.get("likeCount").toString();
                         String viewCount=statistics.get("viewCount").toString();
                         String favoriteCount=statistics.get("favoriteCount").toString();
                         String commentCount=statistics.get("commentCount").toString();

                        System.err.println("dislikeCount:"+dislikeCount);
                        System.err.println("likeCount:"+likeCount);
                        System.err.println("viewCount:"+viewCount);
                        System.err.println("favoriteCount:"+favoriteCount);
                        System.err.println("commentCount:"+commentCount);


                    }
    } catch (Exception ex) {
        ex.printStackTrace();
    }

 }

 }

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.