Friday, April 25, 2014

Web dự báo thời tiết kết quả XML/JSON

Một dịch vụ công cộng dự báo thời tiết khá chi tiết, một kênh tham khảo hay.

http://api.openweathermap.org/data/2.5/forecast?lat=10.0333&lon=105.78333

Kết quả trả về dưới dạng JSON

Nếu muốn XML thì theo địa chỉ bên dưới

http://api.openweathermap.org/data/2.5/forecast?q=can+tho,vn&mode=xml

Các bạn thử phân tích XML xem sao

Thư viện java phân tích JSON

1 // chuy?n chu?i JSON thành ??i t??ng ?? x? lý
2 JSONObject reader = new JSONObject(jsonString);
3 // tham chi?u t?i c?m sys (xem c?u trúc bên trên)
4 JSONObject sys = reader.getJSONObject("sys");
5 // l?y thu?c tính country c?a ??i t??ng sys
6 country.setText(sys.getString("country"));
7 // tham chi?u t?i ?o?n main
8 JSONObject main = reader.getJSONObject("main");
9 // ??c giá tr? ?? ?m
10 humidity.setText("?? ?m: "+ main.getString("humidity") + "%");
11 // hi?n th? toàn b? lên TextViev d??i cùng
12 all.setText(jsonString);
13


Cũng có thể lấy mảng các đối tượng



1 // chuy?n chu?i JSON thành ??i t??ng ?? x? lý
2 JSONObject reader = new JSONObject(jsonString);
3 JSONArray listAll = reader.getJSONArray("list");
4 for (int i = 0; i < listAll.length(); i++) {
5 tv.append(listAll.getJSONObject(i).getString("dt_txt")
6 + ": "+ listAll.getJSONObject(i).getJSONObject("main")
7 .getString("humidity") + "%\n");
8

1 comment:

Translate