0

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.

4
  • gson library simplify your JSON to object parsing. Commented Nov 13, 2013 at 14:31
  • possible duplicate of Parsing JSON Object in Java Commented Nov 13, 2013 at 14:33
  • gson java library would be more than enough. here's the URL: code.google.com/p/google-gson Commented Nov 13, 2013 at 14:33
  • I should have specified, I'm already using the gson library. Commented Nov 13, 2013 at 14:36

2 Answers 2

1

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.
    }
});
Sign up to request clarification or add additional context in comments.

Comments

1

Just open connection from URL and try to read JSON from it:

public static void read() throws IOException{
    InputStream is = null;
    try {
        is = link.openConnection().getInputStream();

        Reader reader = new InputStreamReader(is);

        Map<String, String> jsonObj = gson.fromString(reader, new TypeToken<Map<String, String>>() {}.getType());

        //TODO do next stuff
    } finally{
        if (is != null){
            is.close();
        }
    }
}

If you want, you can bind jsonObj into whatever you want, please read documentation.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.