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/


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