public class ResultEntity implements Serializable {
@SerializedName("IsError")//设置这个 是因为服务器返回的字段叫这个名字,但是这样写违反我们自己的命名规则,所以加上这个注解
private int code;
@SerializedName("InfoMessage")
private String message;
public int getCode() {
return code;
}
public void setCode(int code) {
this.code = code;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
//T泛型,任意对象
public class ResultDataEntity<T> extends ResultEntity implements Serializable {
@SerializedName("ReturnData")
private T data;
public T getData() {
return data;
}
public void setData(T data) {
this.data = data;
}
//以下方法是专门用来转换json to bean or bean to json
public static ResultDataEntity fromJson(String json, Class clazz) {
Gson gson = new Gson();
Type objectType = type(ResultDataEntity.class, clazz);
return gson.fromJson(json, objectType);
}
public String toJson(Class<T> clazz) {
Gson gson = new Gson();
Type objectType = type(ResultDataEntity.class, clazz);
return gson.toJson(this, objectType);
}
static ParameterizedType type(final Class raw, final Type... args) {
return new ParameterizedType() {
public Type getRawType() {
return raw;
}
public Type[] getActualTypeArguments() {
return args;
}
public Type getOwnerType() {
return null;
}
};
}
}
例子
{
"Code": 200,
"Message": "登录成功!",
"Data": {
"IDCardNum": "32098122226112495",
"MemberMobile": "123123444",
"MemberName": "杨x",
"Balance": 460,
"IsEnabled": 1,
"CreatedDate": "2016-12-09 19:43:22.187",
"LastLoginTime": "2016-12-09 19:43:22.187",
"LastLoginIP": "192.168.199.153",
}
}
如何进行解析呢?Data 里面放的是一个用户对象。那么首先我们要创建一个用户类。
public class UserEntity implements Serializable {
/**
* IDCardNum : 32098122226112495
* MemberMobile : 123123444
* MemberName : 杨x
* Balance : 460
* IsEnabled : 1
* CreatedDate : 2016-12-09 19:43:22.187
* LastLoginTime : 2016-12-09 19:43:22.187
* LastLoginIP : 192.168.199.153
*/
@SerializedName("IDCardNum")//可使用该注解 重命名
private String cardNum;
private String MemberMobile;
private String MemberName;
private int Balance;
private int IsEnabled;
private String CreatedDate;
private String LastLoginTime;
private String LastLoginIP;
//各种set get
如何解析呢?
String json ="";//就是服务器返回的数据
ResultDataEntity<UserEntity> userResult =ResultDataEntity.fromJson(json ,UserEntity.class);
UserEntity userEntity =userResult .getData();//取得用户对象,然后进行各种操作
小记
如有更好的方式,请给出建议,如有错误请指出,谢谢