Questo è un esempio molto molto banale (e assolutamente senza fronzoli, né gestione eccezioni o altro) che usa il JSON di Yahoo Weather e la libreria che ho linkato sopra:
codice:public static void main(String[] args) throws Exception { String urlPrefix = "https://query.yahooapis.com/v1/public/yql?q="; String urlSuffix = "&format=json&diagnostics=true&callback="; // Query da eseguire su Yahoo Weather String urlQuery = "select * from weather.forecast where woeid=2502265"; // Costruisco l'URL (avendo l'accortezza di fare l'encoding della query) URL myURL = new URL(urlPrefix + URLEncoder.encode(urlQuery, "UTF-8") + urlSuffix); // Ottengo la connessione al servizio URLConnection con = myURL.openConnection(); // Preparo lo StringBuilder che accoglierà il JSON StringBuilder myJson = new StringBuilder(); // Eseguo la request e leggo il risultato InputStream is = con.getInputStream(); // Essendo che ricevo un JSON (quindi una stringa) posso usare in Reader InputStreamReader reader = new InputStreamReader( is ); BufferedReader br = new BufferedReader( reader ); String line = null; // Leggo finchè ci sono dati da leggere while((line = br.readLine()) != null) { myJson.append( line ); } // Ho finito, chiudo la connessione br.close(); // Costruisco il JSON JSONObject json = new JSONObject( myJson.toString() ); // Ci faccio quel che devo. // Ad esempio, stampo le previsioni per tutti i giorni: JSONObject jsonQuery = json.getJSONObject("query"); JSONObject queryResults = jsonQuery.getJSONObject("results"); JSONObject channel = queryResults.getJSONObject("channel"); JSONObject resItem = channel.getJSONObject("item"); JSONArray forecasts = resItem.getJSONArray("forecast"); for(int i=0; i<forecasts.length(); i++) { JSONObject fc = forecasts.getJSONObject( i ); System.out.println("Data: " + fc.getString("date")); System.out.println("Previsione: " + fc.getString("text")); System.out.println(); } }
Ciao.![]()



Rispondi quotando