在Android中获取天气的JSON响应?

时间:2015-03-12 08:40:20

标签: android json

我开发了天气App,我想使用这个URL, http://api.openweathermap.org/data/2.5/weather?lat=11.11111&lon=22.2222

并获取信息,国家,日出,日落,temp_min,temp_max,名称。 怎么得到回应?

请建议我。 感谢。

{
        sys: {
            message: 1.3106,
            country: "IN",
            sunrise: 1426123283,
            sunset: 1426166271
        },

        main: {
            temp: 306.561,
            temp_min: 306.561,
            temp_max: 306.561,
            pressure: 1016.81,
            sea_level: 1026.98,
            grnd_level: 1016.81,
            humidity: 43
        },

        name: "Sarkhej",
    }

2 个答案:

答案 0 :(得分:1)

JSONObject one = new JSONObject(json);

JSONObject sys = one.getJSONObject("sys");
String message = sys.getString("message");
String country = sys.getString("country");
String sunrise = sys.getString("sunrise");
String sunset = sys.getString("sunset");

JSONObject main = one.getJSONObject("main");
String temp = main.getString("temp");
String temp_min = main.getString("temp_min");
String temp_max = main.getString("temp_max");
String pressure = main.getString("pressure");
...

String name=one.getString("name");

答案 1 :(得分:0)

您必须使用HTTPClient从网址获取数据。

    HttpClient client = new DefaultHttpClient();
                HttpPost post = new HttpPost("http://api.openweathermap.org/data/2.5/weather?lat=11.11111&lon=22.2222");
                try {
                  HttpResponse response= client.execute(post);
                  String json = EntityUtils.toString(response.getEntity());
                    // you can parse this json string and can use it
String country = new JsonObject(json).getJsonObject("sys").getString("country");
                } catch (IOException e) {
                    e.printStackTrace();
                }

不要忘记在清单中添加互联网权限。