簡體   English   中英

使用Retrofit2解析字符串數組

[英]Parsing an array of strings using Retrofit2 for android

我是相對較新的改裝者,在解析一些字符串數組(這是JSON響應的一部分)時遇到問題。

這是JSON響應。

{
"positive": [
    "Relaxed",
    "Uplifted",
    "Hungry",
    "Sleepy",
    "Tingly"
],

"medical": [
    "Eye Pressure",
    "Insomnia",
    "Stress",
    "Fatigue",
    "Headaches"
]
}

我該如何處理?

提前致謝 :)

您需要創建如下的POJO類

public  class  ExampleResponse  {

private  List < String >  positive  =  null;
private  List < String >  medical  =  null;

public  List < String >  getPositive() {
    return  positive;
}

public  void  setPositive(List < String >  positive) {
    this.positive  =  positive;
}

public  List < String >  getMedical() {
    return  medical;
}

public  void  setMedical(List < String >  medical) {
    this.medical  =  medical;
}

}

運行良好。

通過查看您的評論,我認為您的POJO類是正確的,但是將其與Retrofit調用一起使用的方式是錯誤的。 確保POJO類如下所示,

import java.util.List;
import com.google.gson.annotations.Expose;
import com.google.gson.annotations.SerializedName;

public class Foo {

    @SerializedName("positive")
    @Expose
    private List<String> positive = null;
    @SerializedName("medical")
    @Expose
    private List<String> medical = null;

    public List<String> getPositive() {
        return positive;
    }

    public List<String> getMedical() {
        return medical;
    }

}

並使用上面的POJO類。

您的API介面

import retrofit2.Call;
import retrofit2.http.GET;

public interface FooApiInterface {

    /* pass POJO class to Call<> */

    @GET("request/url")
    Call<Foo> getFoo(/* parameters for the request if there any */);

    /* other api calls here */
}

下次使用API​​接口

FooApiInterface client = ...;  // initialization

Call<Foo> fooCall = client.getFoo();

fooCall.enqueue(
         new Callback<Foo>() {
              @Override
              public void onResponse(@NonNull Call<Foo> call, @NonNull Response<Foo> response) {
                 if (response.isSuccessful()) {
                     List<String> positiveList = response.body().getPositive();
                     List<String> medicalList = response.body().getMedical();
                 }
              }

              @Override
              public void onFailure(@NonNull Call<Foo> call, @NonNull Throwable t) {
                     Log.e("error", "API Error ", t);
              }
    }
);

請注意,這里我使用Foo POJO類作為參數而不是List<Strain> (就像您的代碼中使用的那樣)作為Call參數。 如果您按照上述方式修改代碼,則可以消除該錯誤

java.lang.IllegalStateException:應為BEGIN_ARRAY,但在第1行第2列路徑$錯誤處為BEGIN_OBJECT

為了演示,我使用了Foo示例。 根據您的要求進行更改。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM