gson解析通過okhttp擷取的json格式資料(轉載)

來源:互聯網
上載者:User

標籤:

本文採用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/

gson解析通過okhttp擷取的json格式資料(轉載)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.