天天看點

GSON + Okhttp3解析Json資料(以天氣為例子解析)

GSON + Okhttp3解析Json資料

    • 添加依賴庫:
    • 準備JSON資料(由和風天氣提供)

添加依賴庫:

在build.gradle檔案的dependencies中加入以下兩行代碼

implementation 'com.squareup.okhttp3:okhttp:3.4.1'
implementation "com.google.code.gson:gson:2.8.2"
           

準備JSON資料(由和風天氣提供)

{
  "HeWeather6": [
    {
      "basic": {
        "cid": "CN101010100",
        "location": "北京",
        "parent_city": "北京",
        "admin_area": "北京",
        "cnty": "中國",
        "lat": "39.90498734",
        "lon": "116.4052887",
        "tz": "+8.00"
      },
      "update": {
        "loc": "2020-03-26 11:51",
        "utc": "2020-03-26 03:51"
      },
      "status": "ok",
      "now": {
        "cloud": "99",
        "cond_code": "104",
        "cond_txt": "陰",
        "fl": "4",
        "hum": "50",
        "pcpn": "0.0",
        "pres": "1018",
        "tmp": "8",
        "vis": "10",
        "wind_deg": "20",
        "wind_dir": "東北風",
        "wind_sc": "3",
        "wind_spd": "15"
      }
    }
  ]
}
           

準備好了就開始着手幹!

因為準備用GSON來解析首先要寫GSON類

不難看出JSON資料中隻有一個對象就是HeWeather6

下面由4個資料組分别是basic,update,status,now;

在這裡要提一下

@SerializedName注解來将對象裡的屬性跟json裡字段對應值比對起來

不難寫出3個類:

public class Basic {
    @SerializedName("cid")
    public String cid;
    @SerializedName("location")
    public String location;
    @SerializedName("parent_city")
    public String parent_city;
    @SerializedName("admin_area")
    public String admin_area;
    @SerializedName("cnty")
    public String cnty;
    @SerializedName("lat")
    public String lat;
    @SerializedName("lon")
    public String lon;
    @SerializedName("tz")
    public String tz;
}
           
public class Now {
    @SerializedName("cloud")
    public String cloud;
    @SerializedName("cond_code")
    public String cond_code;
    @SerializedName("cond_txt")
    public String cond_txt;
    @SerializedName("fl")
    public String fl;
    @SerializedName("hum")
    public String hum;
    @SerializedName("pcpn")
    public String pcpn;
    @SerializedName("pres")
    public String pres;
    @SerializedName("tmp")
    public String tmp;
    @SerializedName("vis")
    public String vis;
    @SerializedName("wind_deg")
    public String wind_deg;
    @SerializedName("wind_dir")
    public String wind_dir;
    @SerializedName("wind_sc")
    public String wind_sc;
    @SerializedName("wind_spd")
    public String wind_spd;
}
           
public class Update {
    @SerializedName("loc")
    public String loc;
    @SerializedName("utc")
    public String utc;
}
           

還差一個HeWeather6沒處理對不?

public class HeWeather6 {
    public Basic basic;
    
    public Update update;

    public String status;

    public Now now;
}
           

這些就闊以把JSON資料完全轉換成為一個HeWeather6對象

下面就可以寫請求過程和解析過程了:

注意:請求過程基本都放線上程裡面,因為如果擷取的資訊量很大會引起長時間的等待,這樣是非常不友好的!

上代碼:

private void sendRequestHttp(){
	new Thread(new Runnable() {
            @Override
            public void run() {
                try{
                    OkHttpClient client = new OkHttpClient();
                    Request request = new Request.Builder()
                            .url("https://free-api.heweather.net/s6/weather/now?location=beijing&key=5f2528f2af404dd4be77eb55dbbc7af6")//key需要自己申請
                            .build();
                    Response response = client.newCall(request).execute();
                    String Data = response.body().string();
                    HeWeather6 weather6 = getHeWeather6Object(Data);
                    Test(weather6);
                    }catch (Exception e){
            			e.printStackTrace();
        			}
        	}
    }).start();
}
private static HeWeather6 getHeWeather6Object(String Data){
	try{
            JSONObject jsonObject = new JSONObject(Data);//獲得JSON的全部資料
            JSONArray jsonArray = jsonObject.getJSONArray("HeWeather6");
            String weatherContent = jsonArray.getJSONObject(0).toString();//去除頭HeWeather6的資料
            HeWeather6 gson = new Gson().fromJson(weatherContent,HeWeather6.class);//gson為最後處理完畢後的結果
            return gson;
        }catch (Exception e){
            e.printStackTrace();
        }
        return null;
}
public void Test(HeWeather6 weather6){
        if(weather6.status.equals("ok")){
            Log.i("TAG","擷取成功!");
            Log.i("TAG","cid = "+weather6.basic.cid);
            Log.i("TAG","cnty = "+weather6.basic.cnty);
            Log.i("TAG","admin_area = "+weather6.basic.admin_area);
            Log.i("TAG","lat = "+weather6.basic.lat);
            Log.i("TAG","lon = "+weather6.basic.lon);
            Log.i("TAG","location = "+weather6.basic.location);
            Log.i("TAG","tz = "+weather6.basic.tz);
            Log.i("TAG","parent_city = "+weather6.basic.parent_city);
        }else{
            Log.i("TAG","擷取失敗!");
        }

    }
           

驗證階段:

GSON + Okhttp3解析Json資料(以天氣為例子解析)

驗證成功!

此次是關于Web的擷取與解析:關于android版本的解析還有更簡單的方法 由推薦的Android SDK的jar包詳情可參考:關于《第一行代碼》中第十四章的學習總結+遇到的各種坑

由詳細的說明!(不過android SDK的jar都是官方寫好的包,如果換一個api接口可能并沒有官方寫的包。還是要用最基本的方法去擷取!)

要堅持不懈,不怕困難多,就怕敗給了自己!

已經準備學好它,就已經沒有退路了!寫給自己,也送給在學習道路上的學子們