我正在使用REST从数据库中检索信息。
我能够检索一个化妆品对象(我创建的一个类),但我真正想要做的是进行搜索,它应该检索一个化妆品数组。
使用浏览器/失眠向API发出请求,得到一个JSON对象数组(化妆品),如下所示:
[
{
"_id":"6353e8fe5d63726919402cec",
"code":"0000016615656",
-- omitted --
},
{
"_id":"6353e8fe5d63726919402cec",
"code":"0000016615656",
-- omitted --
}
]
我设法让它为一个化妆品对象工作:
我已经声明了一个类,它是一个POJO,其属性如下:
public class Cosmetic implements Serializable {
@SerializedName("_id")
@Expose
private String id;
@SerializedName("code")
@Expose
private String code;
---- omitted ----
}
然后使用和RxJava进行API调用.
final Cosmetic[] cosmetic_result = new Cosmetic[1];
retrofit = new Retrofit.Builder()
.baseUrl(baseUrl)
.addConverterFactory(GsonConverterFactory.create())
.addCallAdapterFactory(RxJava2CallAdapterFactory.create())
.build();
service = retrofit.create(CosmeticsService.class);
// Calling '/prod/beauty/{field}'
Single<Cosmetic> callSync = service.getByName(query);
CompositeDisposable compositeDisposable = new CompositeDisposable();
callSync.subscribeOn(Schedulers.io())
.observeOn(AndroidSchedulers.mainThread())
//https://www.baeldung.com/rxjava-error-handling
.onErrorReturn(Throwable -> productNotFound)
.subscribe(new SingleObserver<Cosmetic>() {
@Override
public void onSubscribe(Disposable d) {
compositeDisposable.add(d);
}
@Override
public void onSuccess(Cosmetic cosmetic) {
System.out.println("API has responded ");
result[0] = cosmetic.getCode();
cosmetic_result[0]=cosmetic;
}
@Override
public void onError(Throwable e) {
e.printStackTrace();
}
});
// While loop necessary to force waiting for the API result
while(result[0]==""){} // DON'T DELETE
return cosmetic_result[0];
因此,这对于这样的一个JSON对象是有效的:
{
"_id":"6353e8fe5d63726919402cec",
"code":"0000016615656"
--- omitted ---
}
如何在Java中为数组执行此操作?
发布于 2022-11-21 00:16:31
通过使用HttpURLConnection解决了这个问题,但我不知道这有多安全。我跟踪本教程,这是我推荐的!
https://stackoverflow.com/questions/74512030
复制相似问题