【问题标题】:Java JSON reading from URL从 URL 读取 Java JSON
【发布时间】:2013-11-13 14:30:04
【问题描述】:

我正在尝试使用我的天气 API 来获取某个区域的天气状况,我认为除了数据解析部分外,我的所有功能都正常运行。

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
    }
}

谁能帮我完成这个简单的小项目,顺便说一句,我是初学者。

【问题讨论】:

标签: java json weather-api


【解决方案1】:

您可以使用javaQuery 更轻松地做到这一点:

$.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.
    }
});

【讨论】:

    【解决方案2】:

    只需从 URL 打开连接并尝试从中读取 JSON:

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

    如果你愿意,你可以将jsonObj绑定到任何你想要的,请阅读documentation

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2012-05-22
      • 1970-01-01
      • 2015-01-20
      • 1970-01-01
      • 2022-09-27
      • 2011-07-19
      • 1970-01-01
      相关资源
      最近更新 更多