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、主界面布局文件

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"  
  2.    xmlns:tools="http://schemas.android.com/tools"  
  3.    android:layout_width="match_parent"  
  4.    android:layout_height="match_parent"  
  5.    android:paddingBottom="@dimen/activity_vertical_margin"  
  6.    android:paddingLeft="@dimen/activity_horizontal_margin"  
  7.    android:paddingRight="@dimen/activity_horizontal_margin"  
  8.    android:paddingTop="@dimen/activity_vertical_margin"  
  9.    tools:context=".MainActivity" >  
  10.   
  11.    <TextView  
  12.       android:id="@+id/textView1"  
  13.       android:layout_width="wrap_content"  
  14.       android:layout_height="wrap_content"  
  15.       android:layout_alignParentLeft="true"  
  16.       android:layout_alignParentTop="true"  
  17.       android:layout_marginTop="15dp"  
  18.       android:text="@string/location"  
  19.       android:textAppearance="?android:attr/textAppearanceMedium" />  
  20.   
  21.    <EditText  
  22.       android:id="@+id/editText1"  
  23.       android:layout_width="wrap_content"  
  24.       android:layout_height="wrap_content"  
  25.       android:layout_alignBottom="@+id/textView1"  
  26.       android:layout_alignParentRight="true"  
  27.       android:ems="10" />  
  28.   
  29.    <TextView  
  30.       android:id="@+id/textView2"  
  31.       android:layout_width="wrap_content"  
  32.       android:layout_height="wrap_content"  
  33.       android:layout_alignLeft="@+id/textView1"  
  34.       android:layout_below="@+id/textView1"  
  35.       android:layout_marginTop="68dp"  
  36.       android:text="@string/country"  
  37.       android:textAppearance="?android:attr/textAppearanceSmall" />  
  38.   
  39.    <TextView  
  40.       android:id="@+id/textView3"  
  41.       android:layout_width="wrap_content"  
  42.       android:layout_height="wrap_content"  
  43.       android:layout_below="@+id/textView2"  
  44.       android:layout_marginTop="19dp"  
  45.       android:text="@string/temperature"  
  46.       android:textAppearance="?android:attr/textAppearanceSmall" />  
  47.   
  48.    <TextView  
  49.       android:id="@+id/textView4"  
  50.       android:layout_width="wrap_content"  
  51.       android:layout_height="wrap_content"  
  52.       android:layout_alignLeft="@+id/textView3"  
  53.       android:layout_below="@+id/textView3"  
  54.       android:layout_marginTop="32dp"  
  55.       android:text="@string/humidity"  
  56.       android:textAppearance="?android:attr/textAppearanceSmall" />  
  57.   
  58.    <TextView  
  59.       android:id="@+id/textView5"  
  60.       android:layout_width="wrap_content"  
  61.       android:layout_height="wrap_content"  
  62.       android:layout_alignLeft="@+id/textView4"  
  63.       android:layout_below="@+id/textView4"  
  64.       android:layout_marginTop="21dp"  
  65.       android:text="@string/pressure"  
  66.       android:textAppearance="?android:attr/textAppearanceSmall" />  
  67.   
  68.    <EditText  
  69.       android:id="@+id/editText2"  
  70.       android:layout_width="wrap_content"  
  71.       android:layout_height="wrap_content"  
  72.       android:layout_above="@+id/textView3"  
  73.       android:layout_toRightOf="@+id/textView3"  
  74.       android:ems="10" >  
  75.   
  76.       <requestFocus />  
  77.    </EditText>  
  78.   
  79.    <EditText  
  80.       android:id="@+id/editText3"  
  81.       android:layout_width="wrap_content"  
  82.       android:layout_height="wrap_content"  
  83.       android:layout_alignBaseline="@+id/textView3"  
  84.       android:layout_alignBottom="@+id/textView3"  
  85.       android:layout_alignLeft="@+id/editText2"  
  86.       android:ems="10" />  
  87.   
  88.    <EditText  
  89.       android:id="@+id/editText4"  
  90.       android:layout_width="wrap_content"  
  91.       android:layout_height="wrap_content"  
  92.       android:layout_above="@+id/textView5"  
  93.       android:layout_alignLeft="@+id/editText1"  
  94.       android:ems="10" />  
  95.   
  96.    <EditText  
  97.       android:id="@+id/editText5"  
  98.       android:layout_width="wrap_content"  
  99.       android:layout_height="wrap_content"  
  100.       android:layout_alignBaseline="@+id/textView5"  
  101.       android:layout_alignBottom="@+id/textView5"  
  102.       android:layout_alignRight="@+id/editText4"  
  103.       android:ems="10" />  
  104.   
  105.    <Button  
  106.       android:id="@+id/button1"  
  107.       android:layout_width="wrap_content"  
  108.       android:layout_height="wrap_content"  
  109.       android:layout_alignLeft="@+id/editText2"  
  110.       android:layout_below="@+id/editText1"  
  111.       android:onClick="open"  
  112.       android:text="@string/weather" />  
  113.   
  114. </RelativeLayout>  

2、定义String.xml

[html]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. <?xml version="1.0" encoding="utf-8"?>  
  2. <resources>  
  3.    <string name="app_name">JSONParser</string>  
  4.    <string name="action_settings">Settings</string>  
  5.    <string name="hello_world">Hello world!</string>  
  6.    <string name="location">Location</string>  
  7.    <string name="country">Country:</string>  
  8.    <string name="temperature">Temperature:</string>  
  9.    <string name="humidity">Humidity:</string>  
  10.    <string name="pressure">Pressure:</string>  
  11.    <string name="weather">Weather</string>  
  12. </resources>  

3、在AndroidManifest.xml中添加internet访问权限。


4、创建一个bean,用于保存天气信息。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.jsonparser.model;  
  2.   
  3. public class WeatherBean {  
  4.       
  5.     private String country;  
  6.     private int Temperature;  
  7.     private int humidity;  
  8.     private int pressure;  
  9.     public String getCountry() {  
  10.         return country;  
  11.     }  
  12.     public void setCountry(String country) {  
  13.         this.country = country;  
  14.     }  
  15.     public int getTemperature() {  
  16.         return Temperature;  
  17.     }  
  18.     public void setTemperature(int temperature) {  
  19.         Temperature = temperature;  
  20.     }  
  21.     public int getHumidity() {  
  22.         return humidity;  
  23.     }  
  24.     public void setHumidity(int humidity) {  
  25.         this.humidity = humidity;  
  26.     }  
  27.     public int getPressure() {  
  28.         return pressure;  
  29.     }  
  30.     public void setPressure(int pressure) {  
  31.         this.pressure = pressure;  
  32.     }  
  33.       
  34.   
  35. }  

5、创建用于访问网络的类,并返回JSON文本。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.jsonparser;  
  2.   
  3. import java.io.BufferedReader;  
  4. import java.io.IOException;  
  5. import java.io.InputStream;  
  6. import java.io.InputStreamReader;  
  7. import java.net.HttpURLConnection;  
  8. import java.net.URL;  
  9.   
  10. public class JSONFetcher {  
  11.       
  12.     private String jsonText = "";  
  13.       
  14.     //本方法通过指定url访问网络数据,并返回JSON格式的string。  
  15.     public  String getJSONText(final URL url){  
  16.           
  17.           
  18.         Thread thread = new Thread(new Runnable(){  
  19.   
  20.             @Override  
  21.             public void run() {  
  22.                 InputStream is =null;  
  23.                 BufferedReader in = null;  
  24.                   
  25.                 try {  
  26.                     HttpURLConnection conn = (HttpURLConnection) url.openConnection();  
  27.                     conn.setReadTimeout(10000 /* milliseconds */);  
  28.                     conn.setConnectTimeout(15000 /* milliseconds */);  
  29.                     conn.setRequestMethod("GET");  
  30.                     conn.setDoInput(true);  
  31.                     conn.connect();  
  32.                       
  33.                     is = conn.getInputStream();  
  34.                     in = new BufferedReader(new InputStreamReader(is));  
  35.                     String line = "";  
  36.                     while((line = in.readLine()) != null){  
  37.                         jsonText += line;  
  38.                     }  
  39.                       
  40.                 } catch (IOException e) {  
  41.                     e.printStackTrace();  
  42.                 }finally{  
  43.                     try {  
  44.                         in.close();  
  45.                         is.close();  
  46.                     } catch (IOException e) {  
  47.                         e.printStackTrace();  
  48.                     }  
  49.                       
  50.                 }  
  51.                   
  52.             }  
  53.               
  54.         });  
  55.           
  56.         thread.start();   
  57.           
  58.         //等待上述线程完成执行后再返回jsonText。  
  59.         try {  
  60.             Thread.sleep(1000);  
  61.         } catch (InterruptedException e) {  
  62.             e.printStackTrace();  
  63.         }  
  64.           
  65.         return jsonText;  
  66.     }  
  67.   
  68. }  

6、创建用于处理JSON文本的类,返回一个WeatherBean对象。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.jsonparser;  
  2.   
  3. import java.net.URL;  
  4.   
  5. import org.json.JSONException;  
  6. import org.json.JSONObject;  
  7.   
  8. import com.example.jsonparser.model.WeatherBean;  
  9.   
  10. public class JSONUtil {  
  11.       
  12.     public static WeatherBean getWeatherBean(URL url){  
  13.           
  14.         String jsonText = new JSONFetcher().getJSONText(url);  
  15.         System.out.println(jsonText);  
  16.         WeatherBean weather = new WeatherBean();  
  17.           
  18.         try {  
  19.             JSONObject weatherJSONObject = new JSONObject(jsonText);  
  20.               
  21.             JSONObject sysJSONObject = weatherJSONObject.getJSONObject("sys");  
  22.             String country = sysJSONObject.getString("country");  
  23.             JSONObject mainJSONObject = weatherJSONObject.getJSONObject("main");  
  24.             int temperature = mainJSONObject.getInt("temp");  
  25.             int pressure = mainJSONObject.getInt("pressure");  
  26.             int humidity = mainJSONObject.getInt("humidity");  
  27.               
  28.             weather.setCountry(country);  
  29.             weather.setTemperature(temperature);  
  30.             weather.setHumidity(humidity);  
  31.             weather.setPressure(pressure);  
  32.         } catch (JSONException e) {  
  33.             System.out.println("test");  
  34.             e.printStackTrace();  
  35.         }  
  36.           
  37.         return weather;  
  38.     }  
  39. }  

7、主布局文件,将WeatherBean中的内容在手机中展现。

[java]  view plain copy 在CODE上查看代码片 派生到我的代码片
  1. package com.example.jsonparser;  
  2.   
  3. import java.net.URL;  
  4.   
  5. import com.example.jsonparser.model.WeatherBean;  
  6.   
  7. import android.os.Bundle;  
  8. import android.app.Activity;  
  9. import android.view.View;  
  10. import android.widget.EditText;  
  11.   
  12. public class MainActivity extends Activity {  
  13.   
  14.     private String url1 = "http://api.openweathermap.org/data/2.5/weather?q=";  
  15.     private EditText location, country, temperature, humidity, pressure;  
  16.   
  17.     @Override  
  18.     protected void onCreate(Bundle savedInstanceState) {  
  19.         super.onCreate(savedInstanceState);  
  20.         setContentView(R.layout.activity_main);  
  21.         location = (EditText) findViewById(R.id.editText1);  
  22.         country = (EditText) findViewById(R.id.editText2);  
  23.         temperature = (EditText) findViewById(R.id.editText3);  
  24.         humidity = (EditText) findViewById(R.id.editText4);  
  25.         pressure = (EditText) findViewById(R.id.editText5);  
  26.     }  
  27.   
  28.     public void open(View view) {  
  29.   
  30.         try {  
  31.             URL url = new URL(url1 + location.getText().toString());  
  32.             System.out.println(url);  
  33.             WeatherBean weatherBean = JSONUtil.getWeatherBean(url);  
  34.             country.setText(weatherBean.getCountry());  
  35.             humidity.setText(weatherBean.getHumidity() + "");  
  36.             pressure.setText(weatherBean.getPressure() + "");  
  37.             temperature.setText(weatherBean.getTemperature() + "");  
  38.             System.out.println("test2");  
  39.   
  40.         } catch (Exception e) {  
  41.             e.printStackTrace();  
  42.         }  
  43.     }  
  44. }  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值