Ошибка модификации Android "Ожидается BEGIN_ARRAY, но было BEGIN_OBJECT" - PullRequest
0 голосов
/ 02 декабря 2018

Я пытаюсь получить список продуктов в формате JSON с помощью Retrofit.Но продолжайте получать эту ошибку.Посмотрел все другие решения, но это не помогло.

"java.lang.IllegalStateException: ожидаемый BEGIN_ARRAY, но был BEGIN_OBJECT в строке 1 пути 2 столбца $"

Iу меня есть аннотации к моему классу модели для базы данных Room, а также реализована передача Parcelable в качестве аргумента другим фрагментам.

ОБНОВЛЕНИЕ:

Я изменил API, как показано ниже.Это работает сейчас.

Вот обновленный JSON:

     [
    {
      "ProductComment": {
        "001": {
          "comment": "A comment",
          "email": "tr...@yahoo.com",
          "generatedProductID": "1111"
        }
      },
      "generatedProductID": "1111",
      "photoUrls": ["https://...", "https://123", "https://333"],
      "title": "title",
      "description": "product desc"
    },
    {
      "ProductComment": {
        "001": {
          "comment": "A comment",
          "email": "bm...@yahoo.com",
          "generatedProductID": "2222"
        },
        "002": {
          "comment": "A Comment",
          "email": "xy...@yahoo.com",
          "generatedProductID": "2222"
        }
      },
      "generatedProductID": "2222",
      "photoUrls": [ "https://...", "https://123", "https://333"],
      "title": "title",
      "description": "product desc"
    }
 ]

[До ОБНОВЛЕНИЯ] мой JSON отформатирован так:

    {
    "00001": {
      "ProductComment": {
        "001": {
          "comment": "A comment",
          "email": "tr...@yahoo.com",
          "generatedProductID": "1111"
        }
      },
      "generatedProductID": "1111",
      "photoUrls": ["https://...", "https://123", "https://333"],
      "title": "title",
      "description": "product desc"
    },
    "00002": {
      "ProductComment": {
        "001": {
          "comment": "A comment",
          "email": "bm...@yahoo.com",
          "generatedProductID": "2222"
        },
        "002": {
          "comment": "A Comment",
          "email": "xy...@yahoo.com",
          "generatedProductID": "2222"
        }
      },
      "generatedProductID": "2222",
      "photoUrls": [ "https://...", "https://123", "https://333"],
      "title": "title",
      "description": "product desc"
    }
  }

Мой класс продукта:

@Entity(tableName = "product")
public class Product implements Parcelable {

    @PrimaryKey
    @NonNull
    private String generatedProductID;
    private String title;
    private String description;
    private List<String> photoUrls;

    @TypeConverters(ProductTypeConverters.class)
    private List<ProductComment> comments;


    public Product() {
    }

    protected Product(Parcel in) {
        generatedProductID = in.readString();
        title = in.readString();
        description = in.readString();
        photoUrls = in.createStringArrayList();
        comments = in.createTypedArrayList(ProductComment.CREATOR);
    }

    public static final Creator<Product> CREATOR = new Creator<Product>() {
        @Override
        public Product createFromParcel(Parcel in) {
            return new Product(in);
        }

        @Override
        public Product[] newArray(int size) {
            return new Product[size];
        }
    };

    @NonNull
    public String getGeneratedProductID() {
        return generatedProductID;
    }

    public void setGeneratedProductID(@NonNull String generatedProductID) {
        this.generatedProductID = generatedProductID;
    }

    public String getTitle() {
        return title;
    }

    public void setTitle(String title) {
        this.title = title;
    }

    public String getDescription() {
        return description;
    }

    public void setDescription(String description) {
        this.description = description;
    }

    public List<String> getPhotoUrls() {
        return photoUrls;
    }

    public void setPhotoUrls(List<String> photoUrls) {
        this.photoUrls = photoUrls;
    }

    public List<ProductComment> getComments() {
        return comments;
    }

    public void setComments(List<ProductComment> comments) {
        this.comments = comments;
    }

    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel dest, int flags) {
        dest.writeString(generatedProductID);
        dest.writeString(title);
        dest.writeString(description);
        dest.writeStringList(photoUrls);
        dest.writeTypedList(comments);
    }

}

Интерфейс:

public interface JsonRetroService {

    @GET("products.json") // relative URL at the end of github url.
    Call<List<Product>> getRemoteProducts();

}

И, наконец, в моем фрагменте:

    Retrofit retrofit = new Retrofit.Builder()
            .baseUrl(PRODUCT_BASE_URL)
            .addConverterFactory(GsonConverterFactory.create())
            .build();

    JsonRetroService service = retrofit.create(JsonRetroService.class);

    Call<List<Product>> call = service.getRemoteProducts();

    call.enqueue(new Callback<List<Product>>() {
        @Override
        public void onResponse(Call<List<Product>> call, Response<List<Product>> response) {

            // First check if the response is not successful. if it' ok continue.
            if (!response.isSuccessful()) {
                Toast.makeText(getActivity(), "Not OK: " + response.code(), Toast.LENGTH_LONG).show();
                return;
            }

            List<Product> products = response.body();

        }

        @Override
        public void onFailure(Call<List<Product>> call, Throwable t) {
            Toast.makeText(getActivity(), "Retrofit Failure..", Toast.LENGTH_LONG).show();
            Log.e(TAG, "onFailure: " , t);
        }
    });
...