Android开发经验谈Android开发AR与Android

Json的泛型T解析

2018-10-28  本文已影响11人  唐小鹏

摘要:开发中,返回的数据格式基本都是message+code+data模式,如登录接口返回数据:{"message":"登录成功","code":"100","data":[{"sex":"女","phone":"15528883251","area":"成都",&

开发中,返回的数据格式基本都是message+code+data模式,如登录接口返回数据:

{ 
"message": "登录成功", 
"code": "100", 
"data": [ 
{ 
"sex": "女", 
"phone": "15528883251", 
"area": "成都", 
"signName": "二哈", 
"age": "18", 
"userIcon": "https://f10.baidu.com/it/u=3661269061,116126203&;fm=72", 
"realName": "樱井莉亚", 
"userInfoID": 9 
} 
]} 

但是,不同接口返回的data都是不一样的,不可能每次都写带code和message的实体类,所以这个时候需要泛型了!网上关于json泛型解析的教程眼花缭乱,有些代码行数都让我瑟瑟发抖!!!自己总结一篇,遛马游泳~!

第一步:首先建立泛型接收实体类:

public class BaseResponseBean<T> { 
public String message; 
public String code; 
public T data; 
public String getMessage() { 
return message; 
} 
public void setMessage(String message) { 
this.message = message; 
} 
public String getCode() { 
return code; 
} 
public void setCode(String code) { 
this.code = code; 
} 
public T getData() { 
return data; 
} 
public void setData(T data) { 
this.data = data; 
}} 

第二步:根据data中的数据类型创建类

public class LoginUser { 
private String sex; 
private String phone; 
private String area; 
private String signName; 
private int age; 
private String userIcon; 
private String realName; 
private Long userInfoID; 
public String getSex() { 
return sex; 
} 
public void setSex(String sex) { 
this.sex = sex; 
} 
public String getPhone() { 
return phone; 
} 
public void setPhone(String phone) { 
this.phone = phone; 
} 
public String getArea() { 
return area; 
} 
public void setArea(String area) { 
this.area = area; 
} 
public String getSignName() { 
return signName; 
} 
public void setSignName(String signName) { 
this.signName = signName; 
} 
public int getAge() { 
return age; 
} 
public void setAge(int age) { 
this.age = age; 
} 
public String getUserIcon() { 
return userIcon; 
} 
public void setUserIcon(String userIcon) { 
this.userIcon = userIcon; 
} 
public String getRealName() { 
return realName; 
} 
public void setRealName(String realName) { 
this.realName = realName; 
} 
public Long getUserInfoID() { 
return userInfoID; 
} 
public void setUserInfoID(Long userInfoID) { 
this.userInfoID = userInfoID; 
}} 

第三步:使用方式:

Type jsonType = new TypeToken<BaseResponseBean<LoginUser>>() {}.getType();
BaseResponseBean<LoginUser> bean = new Gson().fromJson(response, jsonType);
response为需要解析的json字符串,而bean.getData()就是为LoginUser的实例对象.
上一篇下一篇

猜你喜欢

热点阅读