我是Retrofit的新手并尝试使用Retrofit发出POST请求.我的POST请求有一个复杂的JSON正文,如下所示:
负载:
{
"user": {
"personal_info": {
"first_name": "Walter",
"last_name": "White",
"date_of_birth": "1972-01-03 00:00:00 PST"
},
"address_info": {
"address_1": "308 NEGRA ARROYO LANE",
"address_2": "#",
"city": "ALBUQUERQUE",
"state": "NM",
"zip_code": "87104"
},
"contact_info": {
"email": "wwhite@test.com",
"telephone": "88888888888",
"telephone_type_id": 1
},
"employment_info": {
"employer_name": "SELF",
"employment_status_id": 7,
"annual_income": 9000000000000000,
"monthly_income": 750000000000,
"employment_start_year": 0,
"employment_start_month": 0
}
}
}
我将接口定义为
@POST("/users")
void registerUser(@Body User User, Callback<User> cb);
我不确定我的User类应该是什么样的,我希望有效负载与上面提到的相同,到目前为止我的User类为
public class User {
@SerializedName("personal_info")
private PersonalInfo personalInfo;
@SerializedName("address_info")
private AddressInfo addressInfo;
@SerializedName("contact_info")
private ContactInfo contactInfo;
@SerializedName("employment_info")
private EmploymentInfo employmentInfo;
}
我不确定Personalinfo,ContactInfo等应该是JSON请求中提到的所有字段的单独类,还是我应该将它们作为User类中的内部类以及如何使用User类进行Retrofit调用.服务器响应与上面提到的JSON请求完全类似,有1个附加字段,即用户ID.我准备好了POJO课程以获得响应.
我对如何发出POST请求很困惑.在此先感谢您的帮助.
解决方法:
序列化时的User对象将具有此JSON表示:
{
"personal_info": {
"first_name": "Walter",
"last_name": "White",
"date_of_birth": "1972-01-03 00:00:00 PST"
},
"address_info": {
"address_1": "308 NEGRA ARROYO LANE",
"address_2": "#",
"city": "ALBUQUERQUE",
"state": "NM",
"zip_code": "87104"
},
"contact_info": {
"email": "wwhite@test.com",
"telephone": "88888888888",
"telephone_type_id": 1
},
"employment_info": {
"employer_name": "SELF",
"employment_status_id": 7,
"annual_income": 9000000000000000,
"monthly_income": 750000000000,
"employment_start_year": 0,
"employment_start_month": 0
}
}
为了按照问题中的说明构建有效负载,您需要另一个类:
public class UserRequest {
@SerializedName("user")
private User user;
}
在使用Retrofit执行请求时使用它:
@POST("/users")
void registerUser(@Body UserRequest User, Callback<User> cb);