使用 gson 并将您的响应映射到 Java 模型类。
这将是你的模型类 ->
User.java 模型类。
import java.io.Serializable;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang.builder.ToStringBuilder;
public class Users implements Serializable
{
@SerializedName("token")
@Expose
private String token;
@SerializedName("message")
@Expose
private String message;
private final static long serialVersionUID = 3387741697269012981L;
/**
* No args constructor for use in serialization
*
*/
public Users() {
}
/**
*
* @param message
* @param token
*/
public Users(String token, String message) {
super();
this.token = token;
this.message = message;
}
public String getToken() {
return token;
}
public void setToken(String token) {
this.token = token;
}
public Users withToken(String token) {
this.token = token;
return this;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public Users withMessage(String message) {
this.message = message;
return this;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("token", token).append("message", message).toString();
}
}
这是你的根/父类,从那里开始解析。
import java.io.Serializable;
import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;
import org.apache.commons.lang.builder.ToStringBuilder;
public class Root implements Serializable
{
@SerializedName("0")
@Expose
private String _0;
@SerializedName("1")
@Expose
private List<String> _1 = null;
@SerializedName("users")
@Expose
private Users users;
private final static long serialVersionUID = 5880229946098431789L;
/**
* No args constructor for use in serialization
*
*/
public Example() {
}
/**
*
* @param users
* @param _0
* @param _1
*/
public Example(String _0, List<String> _1, Users users) {
super();
this._0 = _0;
this._1 = _1;
this.users = users;
}
public String get0() {
return _0;
}
public void set0(String _0) {
this._0 = _0;
}
public Example with0(String _0) {
this._0 = _0;
return this;
}
public List<String> get1() {
return _1;
}
public void set1(List<String> _1) {
this._1 = _1;
}
public Example with1(List<String> _1) {
this._1 = _1;
return this;
}
public Users getUsers() {
return users;
}
public void setUsers(Users users) {
this.users = users;
}
public Example withUsers(Users users) {
this.users = users;
return this;
}
@Override
public String toString() {
return new ToStringBuilder(this).append("_0", _0).append("_1", _1).append("users", users).toString();
}
}
现在在您接收 Json 映射 json 到解析开始的根/父类的代码处。
Root root = new Gson().fromJson(/*put your json response variable here*/, Root.class);
并使用根对象通过公共 get 方法获取/设置任何数据。