gson解析通過okhttp獲取的json格式數據

第一篇博客,寫的很差,希望大家多多指教!

本文采用okhttp庫獲取聚合網提供的免費接口數據,完成一個手機號碼歸屬地查詢功能。

其請求接口格式如下:


數據返回結果:


首先添加gson和okhttp的引用,gson我是直接下載jar包的:

compile 'com.squareup.okhttp3:okhttp:3.2.0'
compile files('C:/Users/Administrator/AndroidStudioProjects/ExOkhttp/libs/gson-2.3.1.jar')
採用get方法,獲取數據主要代碼如下:

OkHttpClient client=new OkHttpClient();
Request request = new Request.Builder()
        .url("http://apis.juhe.cn/mobile/get?phone="+string+"&key="
        +"2f121eb8bf260e938df638ec3cc2e5d4")
        .get()
        .build();
try{
    Response response = client.newCall(request).execute();
    System.out.println(response.body().string());這裏就可以打印返回的結果了
}catch (Exception e){
   Log.i("json------", e.getMessage()+"/"+e.getCause());
}

解析json數據之前先根據返回數據格式定義一個JsonBean:

public class JsonBean {
    public String resultcode;
    public String reason;
    public Result result;

    public static class Result {
        public String province;
        public String city;
        public String areacode;
        public String zip;
        public String company;
        public String card;
    }
    @Override
    public String toString() {
        return "JsonBean{" +
                "reason='" + reason + '\'' +
                ", resultcode='" + resultcode + '\'' +
                ", result=" + result +
                '}';
    }
}
傳入帶解析的gson數據:

Gson gson = new Gson();
java.lang.reflect.Type type = new TypeToken<JsonBean>() {}.getType();
JsonBean jsonBean = gson.fromJson(response.body().string(), type);
這樣就可以通過jsonBean拿到所以數據了,下面是測試結果:


本文源代碼地址:https://github.com/lovezhupumao/ExOkhttp

okhttp 下載地址:https://github.com/square/okhttp/


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章