开发中客户端时常与服务端打交道,客户端请求参数到服务端,服务端返回响应数据到客户端,开发中用的比较多的就是Json数据传递,从请求到响应的步骤一般是约定数据格式,响应数据进行关系映射,然后对错误数据进行异常处理。
数据格式
一个比较良好的的响应数据应该具备响应码、数据状态描述、具体的响应数据
{
“message”: “正常”,
“responsecode”: 0,
“results”: {
“list”: [
{
“desc”: “HorizontalPicker view 支持文本和icon”,
“id”: “58b7c6da421aa90f131785f0”,
“type”: “Android”,
“who”: “Jason”
},
{
“desc”: “VirtualLayout是一个针对RecyclerView的LayoutManager扩展”,
“id”: “58bb931a421aa90efc4fb65b”,
“type”: “Android”,
“who”: “Jason”
}
],
“total”: 2
}
}
responsecode
responsecode为服务器自定义的响应码
0 | 成功 |
1 | 该用户不存在 |
2 | 充值失败 |
3 | 非法请求 |
4 | 服务器繁忙 |
message
服务端返回数据的状态描述,客户端可以根据需要对操作信息进行显示,当然客户端也可以自定义状态的描述。
results
服务器返回的具体数据,客户端需要对响应数据进行实体类的映射
返回数据映射成实体类
一般来讲,客户端与服务端之间的数据通信大部分是以Json格式进行,我们根据服务端返回的数据来抽象出我们的实体类
public class HttpResult<T> {
private int responsecode;
private String message;
private T results;
public int getResponsecode() {
return responsecode;
}
public void setResponsecode(int responsecode) {
this.responsecode = responsecode;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public T getResults() {
return results;
}
public void setResults(T results) {
this.results = results;
}
}
HttpResult类为所有数据模型的基类,使用泛型results可以保证接收不同的实体模型。
下面定义具体数据的实体模型:
public class ArticleList {
private int total;
private List<Article> list;
public int getTotal() {
return total;
}
public void setTotal(int total) {
this.total = total;
}
public List<Article> getList() {
return list;
}
public void setList(List<Article> list) {
this.list = list;
}
}
public class Article {
private String id;
private String type;
private String who;
private String desc;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public String getWho() {
return who;
}
public void setWho(String who) {
this.who = who;
}
public String getDesc() {
return desc;
}
public void setDesc(String desc) {
this.desc = desc;
}
}
映射实体类定义完毕之后,我们使用retrofit定义数据请求接口: