我将在我的应用程序中使用rxjava进行改造。我正在处理他的事情:我在POST API上使用这种json格式将数据发送到服务器:
{
"user":{
"email":"0665587777",
"password":"password",
"password_confirmation":"password",
"user_type":"patient"
},
"profile":{
"first_name":"David",
"lastname":"Jackson bil",
"gender":"Male",
"national_id":"22111"
}
}
并获取此json格式以从服务器获取数据:
{
"id": 37,
"email": "0665587777",
"created_at": "2017-05-12T13:11:58.278Z",
"updated_at": "2017-05-12T13:11:58.278Z",
"enabled": false,
"admin": false,
"user_type": "patient",
"googletoken": null
}
为此我创建了一个名为register的对象并实现如下:
public class register {
@SerializedName("user")
User user=new User();
@SerializedName("profile")
patient patient=new patient();
}
我在我的界面中设置了这样的API调用:
@POST("api/users")
//Call<SOAnswersResponse> getAnswer();
Observable<register> CreateUser(@Body register user);
并实现像这样的Retrofit客户端:
public class RetrofitClient {
private static Retrofit retrofit=null;
public static Retrofit getClient(String baseUrl){
if(retrofit==null){
retrofit=new Retrofit.Builder()
.baseUrl(baseUrl)
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.addConverterFactory(GsonConverterFactory.create())
.build();
}
return retrofit;
}
}
这就是我在活动中所做的一切:
public class CreateUser extends AppCompatActivity {
private SOService mService;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_create_user);
mService= ApiUtils.getSOService();
loadAnwser();
}
private void loadAnwser() {
Observer<register> myObserver= new Observer<register>() {
@Override
public void onSubscribe(@NonNull Disposable d) {
}
@Override
public void onNext(@NonNull register register) {
User user=register.getUser();
Log.d("Retroit_Result",user.toString());
}
@Override
public void onError(@NonNull Throwable e) {
Log.d("Retroit_Result","Error"+e.getMessage());
}
@Override
public void onComplete() {
}
};
mService=ApiUtils.getSOService();
User user=new User();
patient patient=new patient();
register reg=new register();
patient.setFirst_name("Hussssein");
patient.setLast_name("Ojaaaghi");
user.setEmail("55662266");
patient.setGender("Male");
patient.setNational_id("123222322");
user.setPassword("password");
user.setPassword_confirmation("password");
user.setUser_type("patient");
reg.setPatient(patient);
reg.setUser(user);
mService.CreateUser(reg)
.subscribeOn(Schedulers.newThread())
.observeOn(AndroidSchedulers.mainThread())
.subscribe(myObserver);
}
}
现在问题是我在onNext方法中得到null?
答案 0 :(得分:0)
您正在发布一个寄存器对象,但也期望API调用返回一个寄存器对象,例如
Observable<register> CreateUser(@Body register user);
然而,您期望的JSON片段不是注册类型
{ &#34; id&#34;:37, &#34;电子邮件&#34;:&#34; 0665587777&#34;, &#34; created_at&#34;:&#34; 2017-05-12T13:11:58.278Z&#34;, &#34; updated_at&#34;:&#34; 2017-05-12T13:11:58.278Z&#34;, &#34;启用&#34;:false, &#34; admin&#34;:false, &#34; user_type&#34;:&#34;患者&#34;, &#34; googletoken&#34;:null }
您需要创建一个表示此数据的新响应对象,并更改返回类型,例如
Observable<RegisterResponse> CreateUser(@Body register user);