pass a JsonArray to an ArryList

0

I have the following code:

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));

Now this generates a Json of the following format:

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

My question is how can I save this Json in an ArrayList or in a data structure, check in a Json editor online and I have an array structure in the code I try to access using a:

getJSONArray("items")

But it only returns me a position and it is blank

    
asked by Bryan Saltos 06.10.2018 в 00:40
source

1 answer

1

I'll give you an example of how you can go through it, with this you can get the values and save them in an ArrayList for example.

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();
    }

 }

 }
    
answered by 06.10.2018 / 02:08
source