Search code examples
javajsonweather-api

Java JSON reading from URL


I'm trying to use my weather API to get the weather condition for an area, I think I have everything functioning except for the data parsing part.

import java.net.*;
import java.io.*;
import com.google.gson.*;

public class URLReader {

    public static URL link;

    public static void main(String[] args) {
        try{
            open();
            read();
        }catch(IOException e){}
    }

    public static void open(){
        try{
            link = new URL("http://api.wunderground.com/api/54f05b23fd8fd4b0/geolookup/conditions/forecast/q/US/CO/Denver.json");
        }catch(MalformedURLException e){}
    }
    public static void read() throws IOException{
        //little bit stuck here
    }
}

Can anyone help me to finish this simple little project, I'm a beginner btw.


Solution

  • You can use javaQuery to do this more easily:

    $.getJSON("http://api.wunderground.com/api/54f05b23fd8fd4b0/geolookup/conditions/forecast/q/US/CO/Denver.json", null, new Function() {
        @Override
        public void invoke($ j, Object... args) {
            //if you are expecting a JSONObject, use:
            JSONObject json = (JSONObject) args[0];
    
            //otherwise, it would be: JSONArray json = (JSONArray) args[0];
    
            //Then to more easily parse the JSON, do this:
            Map<String, ?> map = $.map(json)
    
            //if you are using an array instead, you can use: Object[] array = $.makeArray(json);
    
            //Now just iterate through your map (or list) to get the data you want to parse.
        }
    });