我是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);
总结 以上是内存溢出为你收集整理的android – 使用复杂的JSON进行Retrofit POST请求全部内容,希望文章能够帮你解决android – 使用复杂的JSON进行Retrofit POST请求所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)