我必须与API进行交互,而且响应格式(从我读过的内容)看起来结构很差。我发现谷歌小组回复了一个类似的问题here,但我在实现一个Response类来处理Gson.fromJson时遇到了麻烦。有没有一个例子我错过了那个?
{
"response":{
"reference": 1023,
"data":{
"user":{
"id":"210",
"firstName":"john",
"lastName":"smith",
"email":"pocahontas@gmail.com",
"phone":"",
"linkedid":{
"id":"238"
}
}
}
}
}
答案 0 :(得分:44)
JSON对象{}
可以由Map<String, Object>
或Javabean类表示。这是一个使用Javabean的例子。
public class ResponseData {
private Response response;
// +getter+setter
public static class Response {
private int reference;
private Data data;
// +getters+setters
}
public static class Data {
private User user;
// +getter+setter
}
public static class User {
private String id;
private String firstName;
private String lastName;
private String email;
private String phone;
private Linkedid linkedid;
// +getters+setters
}
public static class Linkedid {
private String id;
// +getter+setter
}
}
按如下方式使用:
ResponseData responseData = new Gson().fromJson(json, ResponseData.class);