How to read a JSON from a URL

0

I have to read this Json: JSON in question

For this I have the following code and yet I do not see the error. Can someone help? To be able, I would like to do it with the Gson google libraries

public class JsonUrlReader {

    public BicingInfo refreshBicingInfo(String url){
        try {
            InputStreamReader reader = new InputStreamReader(url.openStream());
            BicingInfo dto = new Gson().fromJson(reader, BicingInfo.class);
            return dto;
        }catch (IOException e){
            e.printStackTrace();
        }
    }
}
    
asked by Xavi 14.07.2017 в 00:08
source

1 answer

3

I made a small program that suits your needs, I hope it works for you:

public static void obtieneJson()
{
    try
    {
        //creamos una URL donde esta nuestro webservice
        URL url = new URL("http://wservice.viabicing.cat/v2/stations");
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        //indicamos por que verbo HTML ejecutaremos la solicitud
        conn.setRequestMethod("GET");
        conn.setRequestProperty("Accept", "application/json");
        if (conn.getResponseCode() != 200) 
        {
            //si la respuesta del servidor es distinta al codigo 200 lanzaremos una Exception
            throw new RuntimeException("Failed : HTTP error code : " + conn.getResponseCode());
        }
        BufferedReader br = new BufferedReader(new InputStreamReader((conn.getInputStream())));
        //creamos un StringBuilder para almacenar la respuesta del web service
        StringBuilder sb = new StringBuilder();
        int cp;
        while ((cp = br.read()) != -1)
        {
          sb.append((char) cp);
        }
        //en la cadena output almacenamos toda la respuesta del servidor
        String output = sb.toString();
        //convertimos la cadena a JSON a traves de la libreria GSON
        JsonObject json = new Gson().fromJson(output,JsonObject.class);
        //imprimimos como Json
        System.out.println("salida como JSON" +  json);
        //imprimimos como String
        System.out.println("salida como String : " +output);

        conn.disconnect();
    }
    catch(Exception e)
    {
        System.out.println(e.getMessage());
    }
}

Greetings

    
answered by 14.07.2017 в 04:12