使用okhttp的 post请求得到json数据, 那么怎么去把这组json数据解析出来呢?
首先使用okhttp去post请求到数据
点击事件以后
{
//创建网络处理的对象
OkHttpClient client =new OkHttpClient.Builder()
.readTimeout(5, TimeUnit.SECONDS)
.build();
//post请求来获得数据
//创建一个RequestBody,存放重要数据的键值对
RequestBody body =new FormBody.Builder()
.add("*********", "**********")//(****)为某个App接口文档里的数据(必填)
.add("**********", "*********").build();
//创建一个请求对象,传入URL地址和相关数据的键值对的对象
Request request =new Request.Builder()
.url("*************************")//App接口文档的网站名(必填)
.post(body).build();
//创建一个能处理请求数据的操作类
Call call = client.newCall(request);
//使用异步任务的模式请求数据
call.enqueue(new Callback() {
@Override
public void onFailure(Call call, IOException e) {
Log.e("TAG", "错误信息" + e.toString());
}
@Override
public void onResponse(Call call, Response response)throws IOException {
Log.e("TAG", response.body().string());
});
然后得到一组json数据 如果感觉格式看着有点乱,就把它复制到在线json检验格式化工具里格式化一下
{
"success": "1",
"dz": {
"company_id": "10",
"title": "wecan",
"is_complete": "1"
},
"dy": {
"user_id": "12",
"is_complete": "1"
}
}
定义一个类,声明json里面的数据 (类名自定义)
public class LoginResp {
private Stringsuccess;
private Dzdz;
private Dydy;
public StringgetSuccess() {
return success;
}
public void setSuccess(String success) {
this.success = success;
}
public void setDz(Dz dz){
this.dz = dz;
}
public DzgetDz(){
return dz;
}
public void setDy(Dy dy){
this.dy = dy;
}
public DygetDy(){
return dy;
}
}
再定义一个Dz类 (类名自定义)
public class Dz {
private int company_id;
private Stringtitle;
private int is_complete;
public void setcompany_id(int company_id){
this.company_id = company_id;
}
public int getCompany_id(){
return company_id;
}
public void setTitle(String title){
this.title = title;
}
public StringgetTitle(){
return title;
}
public void setIs_complete(int is_complete){
this.is_complete = is_complete;
}
public int is_complete(){
return is_complete;
}
}
再定义一个Dy类 (类名自定义)
public class Dy {
private int user_id;
private int is_complete1;
public void setUser_id(int user_id){
this.user_id = user_id;
}
public int getUser_id(){
return user_id;
}
public void setIs_complete1(int is_complete1){
this.is_complete1 = is_complete1;
}
public int getIs_complete1(){
return is_complete1;
}
}
在onResponse方法里写以下代码
String json = response.body().string();
LoginResp loginResp =new Gson().fromJson(json,LoginResp.class);
System.out.println("success: "+loginResp.getSuccess());
System.out.println("company_id: "+loginResp.getDz().getCompany_id());
System.out.println("title: "+loginResp.getDz().getTitle());
System.out.println("is_complete: "+loginResp.getDz().getCompany_id());
System.out.println("user_id: "+loginResp.getDy().getUser_id());
System.out.println("is_complete1: "+loginResp.getDy().getIs_complete1());
注意:写完解析json数据的代码后,把Log.e("TAG", response.body().string()); 这行代码注释掉,
不然程序会闪退。
运行结果:
System.out: success: 1
System.out: company_id: 10
System.out: title: wecan
System.out: is_complete: 10
System.out: user_id: 12
System.out: is_complete1: 0
网友评论