gpt4 book ai didi

java - 如何将 Retrofit 和 RxJava 与多个 pojo 类一起使用?

转载 作者:行者123 更新时间:2023-12-02 01:26:27 26 4
gpt4 key购买 nike

我在 android studio 上开发了一个 android 应用程序。我用的是java。

我想使用来自开放食品事实的API:https://fr.openfoodfacts.org/api/v0/produit/3029330003533.json

但我只知道如何使用retrofit和Rxjava仅使用一个pojo类。

我使用这个网站来创建pojo类:http://pojo.sodhanalibrary.com但他创建了很多 pojo 类,我不知道它是否正确以及如何使用它?

接下来你可以看到我有大量的 POJO 类。

POJO class

最佳答案

使用JsonSchema用于为您正在使用的解析库(GSON/Jackson 等)生成 pojo 以及用于调用用户 RxJava 的 Api并像这样进行改造

创建 Pojo


import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.annotation.JsonPropertyOrder;
import com.foodit.data.remote.wrapper.SignupDetailsWrapper;

@JsonInclude(JsonInclude.Include.NON_NULL)
@JsonPropertyOrder({
"code",
"msg",
"details"
})
public class LoginResponse {

@JsonProperty("code")
private int code;
@JsonProperty("msg")
private String msg;
@JsonProperty("details")
private List<LoginDetailsWrapper> details = new ArrayList<LoginDetailsWrapper>();

@JsonProperty("code")
public int getCode() {
return code;
}

@JsonProperty("code")
public void setCode(int code) {
this.code = code;
}

@JsonProperty("msg")
public String getMsg() {
return msg;
}

@JsonProperty("msg")
public void setMsg(String msg) {
this.msg = msg;
}

@JsonProperty("details")
public List<LoginDetailsWrapper> getDetails() {
return details;
}

@JsonProperty("details")
public void setDetails(List<LoginDetailsWrapper> details) {
this.details = details;
}

}

像这样在ApiInterface中定义Api

 @FormUrlEncoded
@POST("login")
Observable<LoginResponse> userLogin(@Field("device_id") String device_id, @Field("device_type") String device_type,
@Field("username") String username, @Field("password") String password
);

并像这样调用 api


@Override
public void userLogin(String device_id, String device_type, String username, String password) {
getCompositeDisposable().add(loginActivtiyInteractor.userLogin(device_id, device_type, username, password)
.subscribeOn(Schedulers.io()).observeOn(AndroidSchedulers.mainThread())
.subscribe(loginResponse -> {
if (loginResponse != null) {
if (loginResponse.getCode() == 1) {
getMvpView().hideLoading();
getMvpView().updateView(loginResponse);
} else {
getMvpView().hideLoading();
getMvpView().onError(loginResponse.getMsg());
}
}
}, throwable -> {
throwable.printStackTrace();
getMvpView().onError(throwable.getLocalizedMessage());
getMvpView().hideLoading();
}));
}

希望对您有所帮助。

关于java - 如何将 Retrofit 和 RxJava 与多个 pojo 类一起使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56849896/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com