當前位置:
首頁 >
前端技术
> javascript
>内容正文
javascript
JSON之三:获取JSON文本并解释(以google的天气API为例)
生活随笔
收集整理的這篇文章主要介紹了
JSON之三:获取JSON文本并解释(以google的天气API为例)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
google提供了天氣的api,以廣州天氣為例,地址為:
http://api.openweathermap.org/data/2.5/weather?q=guangzhou
返回的結果為:
{ "coord": { "lon": 113.25, "lat": 23.12 }, "sys": { "message": 0.2088, "country": "CN", "sunrise": 1400017567, "sunset": 1400065233 }, "weather": [ { "id": 501, "main": "Rain", "description": "moderate rain", "icon": "10d" } ], "base": "cmc stations", "main": { "temp": 299.818, "temp_min": 299.818, "temp_max": 299.818, "pressure": 1004.54, "sea_level": 1014.72, "grnd_level": 1004.54, "humidity": 97 }, "wind": { "speed": 4.42, "deg": 201.501 }, "rain": { "3h": 6 }, "clouds": { "all": 44 }, "dt": 1400055192, "id": 1809858, "name": "Guangzhou", "cod": 200 }因此,在本范例中,寫一個天氣查詢的DEMO,用于輸入地點,并查詢天氣情況。
項目更新請見:https://code.csdn.net/jediael_lu/googleweatherparse/tree/master
效果如下:
詳細步驟如下:
1、主界面布局文件
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"android:paddingBottom="@dimen/activity_vertical_margin"android:paddingLeft="@dimen/activity_horizontal_margin"android:paddingRight="@dimen/activity_horizontal_margin"android:paddingTop="@dimen/activity_vertical_margin"tools:context=".MainActivity" ><TextViewandroid:id="@+id/textView1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignParentLeft="true"android:layout_alignParentTop="true"android:layout_marginTop="15dp"android:text="@string/location"android:textAppearance="?android:attr/textAppearanceMedium" /><EditTextandroid:id="@+id/editText1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBottom="@+id/textView1"android:layout_alignParentRight="true"android:ems="10" /><TextViewandroid:id="@+id/textView2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/textView1"android:layout_below="@+id/textView1"android:layout_marginTop="68dp"android:text="@string/country"android:textAppearance="?android:attr/textAppearanceSmall" /><TextViewandroid:id="@+id/textView3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_below="@+id/textView2"android:layout_marginTop="19dp"android:text="@string/temperature"android:textAppearance="?android:attr/textAppearanceSmall" /><TextViewandroid:id="@+id/textView4"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/textView3"android:layout_below="@+id/textView3"android:layout_marginTop="32dp"android:text="@string/humidity"android:textAppearance="?android:attr/textAppearanceSmall" /><TextViewandroid:id="@+id/textView5"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/textView4"android:layout_below="@+id/textView4"android:layout_marginTop="21dp"android:text="@string/pressure"android:textAppearance="?android:attr/textAppearanceSmall" /><EditTextandroid:id="@+id/editText2"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/textView3"android:layout_toRightOf="@+id/textView3"android:ems="10" ><requestFocus /></EditText><EditTextandroid:id="@+id/editText3"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBaseline="@+id/textView3"android:layout_alignBottom="@+id/textView3"android:layout_alignLeft="@+id/editText2"android:ems="10" /><EditTextandroid:id="@+id/editText4"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_above="@+id/textView5"android:layout_alignLeft="@+id/editText1"android:ems="10" /><EditTextandroid:id="@+id/editText5"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignBaseline="@+id/textView5"android:layout_alignBottom="@+id/textView5"android:layout_alignRight="@+id/editText4"android:ems="10" /><Buttonandroid:id="@+id/button1"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_alignLeft="@+id/editText2"android:layout_below="@+id/editText1"android:onClick="open"android:text="@string/weather" /></RelativeLayout>2、定義String.xml <?xml version="1.0" encoding="utf-8"?> <resources><string name="app_name">JSONParser</string><string name="action_settings">Settings</string><string name="hello_world">Hello world!</string><string name="location">Location</string><string name="country">Country:</string><string name="temperature">Temperature:</string><string name="humidity">Humidity:</string><string name="pressure">Pressure:</string><string name="weather">Weather</string> </resources>
3、在AndroidManifest.xml中添加internet訪問權限。
4、創建一個bean,用于保存天氣信息。
package com.example.jsonparser.model;public class WeatherBean {private String country;private int Temperature;private int humidity;private int pressure;public String getCountry() {return country;}public void setCountry(String country) {this.country = country;}public int getTemperature() {return Temperature;}public void setTemperature(int temperature) {Temperature = temperature;}public int getHumidity() {return humidity;}public void setHumidity(int humidity) {this.humidity = humidity;}public int getPressure() {return pressure;}public void setPressure(int pressure) {this.pressure = pressure;}}5、創建用于訪問網絡的類,并返回JSON文本。 package com.example.jsonparser;import java.io.BufferedReader; import java.io.IOException; import java.io.InputStream; import java.io.InputStreamReader; import java.net.HttpURLConnection; import java.net.URL;public class JSONFetcher {private String jsonText = "";//本方法通過指定url訪問網絡數據,并返回JSON格式的string。public String getJSONText(final URL url){Thread thread = new Thread(new Runnable(){@Overridepublic void run() {InputStream is =null;BufferedReader in = null;try {HttpURLConnection conn = (HttpURLConnection) url.openConnection();conn.setReadTimeout(10000 /* milliseconds */);conn.setConnectTimeout(15000 /* milliseconds */);conn.setRequestMethod("GET");conn.setDoInput(true);conn.connect();is = conn.getInputStream();in = new BufferedReader(new InputStreamReader(is));String line = "";while((line = in.readLine()) != null){jsonText += line;}} catch (IOException e) {e.printStackTrace();}finally{try {in.close();is.close();} catch (IOException e) {e.printStackTrace();}}}});thread.start(); //等待上述線程完成執行后再返回jsonText。try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}return jsonText;}}
6、創建用于處理JSON文本的類,返回一個WeatherBean對象。 package com.example.jsonparser;import java.net.URL;import org.json.JSONException; import org.json.JSONObject;import com.example.jsonparser.model.WeatherBean;public class JSONUtil {public static WeatherBean getWeatherBean(URL url){String jsonText = new JSONFetcher().getJSONText(url);System.out.println(jsonText);WeatherBean weather = new WeatherBean();try {JSONObject weatherJSONObject = new JSONObject(jsonText);JSONObject sysJSONObject = weatherJSONObject.getJSONObject("sys");String country = sysJSONObject.getString("country");JSONObject mainJSONObject = weatherJSONObject.getJSONObject("main");int temperature = mainJSONObject.getInt("temp");int pressure = mainJSONObject.getInt("pressure");int humidity = mainJSONObject.getInt("humidity");weather.setCountry(country);weather.setTemperature(temperature);weather.setHumidity(humidity);weather.setPressure(pressure);} catch (JSONException e) {System.out.println("test");e.printStackTrace();}return weather;} }
7、主布局文件,將WeatherBean中的內容在手機中展現。 package com.example.jsonparser;import java.net.URL;import com.example.jsonparser.model.WeatherBean;import android.os.Bundle; import android.app.Activity; import android.view.View; import android.widget.EditText;public class MainActivity extends Activity {private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=";private EditText location, country, temperature, humidity, pressure;@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);location = (EditText) findViewById(R.id.editText1);country = (EditText) findViewById(R.id.editText2);temperature = (EditText) findViewById(R.id.editText3);humidity = (EditText) findViewById(R.id.editText4);pressure = (EditText) findViewById(R.id.editText5);}public void open(View view) {try {URL url = new URL(url1 + location.getText().toString());System.out.println(url);WeatherBean weatherBean = JSONUtil.getWeatherBean(url);country.setText(weatherBean.getCountry());humidity.setText(weatherBean.getHumidity() + "");pressure.setText(weatherBean.getPressure() + "");temperature.setText(weatherBean.getTemperature() + "");System.out.println("test2");} catch (Exception e) {e.printStackTrace();}} }
總結
以上是生活随笔為你收集整理的JSON之三:获取JSON文本并解释(以google的天气API为例)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: JSON入门之二:org.json的基本
- 下一篇: 【搜索引擎基础知识1】搜索引擎的技术架构