com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: ожидается BEGIN_OBJECT, но в строке 1 путь 3 столбца 3 $ [0] ошибка Gson - PullRequest
1 голос
/ 11 июля 2019

Ошибка возникает всякий раз, когда я запрашиваю метод @Post. Метод @Get будет работать нормально. хорошо, ответ приходит хорошо в PostMan тоже. Может кто-нибудь помочь мне, почему это происходит. Заголовки используются заголовок («Content-Type», «application / json») заголовок («Принять», «Приложение / JSON»)

Метод запроса моего поста -

@POST("api/product/getProductbyCategory")
    Observable<List<CategoryProductResponse>> getProductListOnCategory(@Query("category_id") String categoryId);

Ответ, который я получаю в PostMan-

 [{"product_id":"50","name":"Lovinn Milk pouch","description":"Milk for daily use. Milk will be delivered next day of the order, Orders placed after 10:00 PM will ..","meta_title":"Milk pouch","meta_description":"Milk pouch","meta_keyword":"Milk pouch","tag":"Milk pouch","model":"Lovinn Milk Pouch","sku":"","upc":"","ean":"","jan":"","isbn":"","mpn":"","location":"BANGALORE","quantity":"10","stock_status":"Pre-Order","image":"catalog\/Milk_Pouch.png","manufacturer_id":"11","manufacturer":"Lovinn","price":"20.0000","special":null,"reward":null,"points":"0","tax_class_id":"9","date_available":"2019-06-22","weight":"0.00000000","weight_class_id":"1","length":"10.00000000","width":"0.00000000","length_class_id":"3","subtract":"1","rating":0,"reviews ":0,"sort_order":"1","viewed":"25"},{"product_id":"60","name":"Buffalo Milk 1 ltr","description":"Farm Fresh Pure Buffalo Raw Milk..","meta_title":"Farm Fresh Pure Buffalo Raw Milk","meta_description":"Farm Fresh Pure Buffalo Raw Milk","meta_keyword":"Farm Fresh Pure Buffalo Raw Milk","tag":"Farm Fresh Pure Buffalo Raw Milk","model":"Buffalo Milk One ltr","sku":"","upc":"","ean":"","jan":"","isbn":"","mpn":"","location":"","quantity":"5","stock_status":"2-3 Days","image":"catalog\/Buffalo-Milk.png","manufacturer_id":"11","manufacturer":"Lovinn","price":"40.0000","special":null,"reward":null,"points":"0","tax_class_id":"9","date_available":"2019-06-22","weight":"0.00000000","weight_class_id":"1","length":"0.00000000","width":"0.00000000","length_class_id":"1","subtract":"1","rating":0,"reviews ":0,"sort_order":"1","viewed":"7"},{"product_id":"57","name":"Lovinn 0.25 liter","description":"Milk for daily use. Milk will be delivered next day of the order, Orders placed after 10:00 PM will ..","meta_title":"Milk","meta_description":"Lovinn milk","meta_keyword":"cow milk","tag":"milk,cow milk, lovinn,","model":"Lovinn Milk Pouch1","sku":"","upc":"","ean":"","jan":"","isbn":"","mpn":"","location":"","quantity":"10","stock_status":"2-3 Days","image":"catalog\/Milk_Pouch.png","manufacturer_id":"11","manufacturer":"Lovinn","price":"10.0000","special":null,"reward":null,"points":"0","tax_class_id":"9","date_available":"2019-06-22","weight":"200.00000000","weight_class_id":"1","length":"0.00000000","width":"0.00000000","length_class_id":"1","subtract":"1","rating":0,"reviews ":0,"sort_order":"1","viewed":"7"},{"product_id":"59","name":"Buffalo Milk","description":"Farm Fresh Pure Buffalo Raw Milk..","meta_title":"Farm Fresh Pure Buffalo Raw Milk","meta_description":"Farm Fresh Pure Buffalo Raw Milk","meta_keyword":"Farm Fresh Pure Buffalo Raw Milk","tag":"Buffalo Raw Milk","model":"Buffalo Milk half ltr","sku":"","upc":"","ean":"","jan":"","isbn":"","mpn":"","location":"","quantity":"4","stock_status":"2-3 Days","image":"catalog\/Buffalo-Milk.png","manufacturer_id":"11","manufacturer":"Lovinn","price":"25.0000","special":null,"reward":null,"points":"0","tax_class_id":"9","date_available":"2019-06-22","weight":"0.00000000","weight_class_id":"1","length":"0.00000000","width":"3.00000000","length_class_id":"3","subtract":"1","rating":0,"reviews ":0,"sort_order":"1","viewed":"8"}]

Pojo класс-

   import com.google.gson.annotations.Expose;
    import com.google.gson.annotations.SerializedName;
    public class CategoryProductResponse{
   @SerializedName("product_id")
@Expose
private String productId;
@SerializedName("name")
@Expose
private String name;
@SerializedName("description")
@Expose
private String description;
@SerializedName("meta_title")
@Expose
private String metaTitle;
@SerializedName("meta_description")
@Expose
private String metaDescription;
@SerializedName("meta_keyword")
@Expose
private String metaKeyword;
@SerializedName("tag")
@Expose
private String tag;
@SerializedName("model")
@Expose
private String model;
@SerializedName("sku")
@Expose
private String sku;
@SerializedName("upc")
@Expose
private String upc;
@SerializedName("ean")
@Expose
private String ean;
@SerializedName("jan")
@Expose
private String jan;
@SerializedName("isbn")
@Expose
private String isbn;
@SerializedName("mpn")
@Expose
private String mpn;
@SerializedName("location")
@Expose
private String location;
@SerializedName("quantity")
@Expose
private String quantity;
@SerializedName("stock_status")
@Expose
private String stockStatus;
@SerializedName("image")
@Expose
private String image;
@SerializedName("manufacturer_id")
@Expose
private String manufacturerId;
@SerializedName("manufacturer")
@Expose
private String manufacturer;
@SerializedName("price")
@Expose
private String price;
@SerializedName("special")
@Expose
private Object special;
@SerializedName("reward")
@Expose
private Object reward;
@SerializedName("points")
@Expose
private String points;
@SerializedName("tax_class_id")
@Expose
private String taxClassId;
@SerializedName("date_available")
@Expose
private String dateAvailable;
@SerializedName("weight")
@Expose
private String weight;
@SerializedName("weight_class_id")
@Expose
private String weightClassId;
@SerializedName("length")
@Expose
private String length;
@SerializedName("width")
@Expose
private String width;
@SerializedName("length_class_id")
@Expose
private String lengthClassId;
@SerializedName("subtract")
@Expose
private String subtract;
@SerializedName("rating")
@Expose
private Integer rating;
@SerializedName("reviews ")
@Expose
private Integer reviews;
@SerializedName("sort_order")
@Expose
private String sortOrder;
@SerializedName("viewed")
@Expose
private String viewed;

public String getProductId() {
return productId;
}

public void setProductId(String productId) {
this.productId = productId;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}

public String getDescription() {
return description;
}

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

public String getMetaTitle() {
return metaTitle;
}

public void setMetaTitle(String metaTitle) {
this.metaTitle = metaTitle;
}

public String getMetaDescription() {
return metaDescription;
}

public void setMetaDescription(String metaDescription) {
this.metaDescription = metaDescription;
}

public String getMetaKeyword() {
return metaKeyword;
}

public void setMetaKeyword(String metaKeyword) {
this.metaKeyword = metaKeyword;
}

public String getTag() {
return tag;
}

public void setTag(String tag) {
this.tag = tag;
}

public String getModel() {
return model;
}

public void setModel(String model) {
this.model = model;
}

public String getSku() {
return sku;
}

public void setSku(String sku) {
this.sku = sku;
}

public String getUpc() {
return upc;
}

public void setUpc(String upc) {
this.upc = upc;
}

public String getEan() {
return ean;
}

public void setEan(String ean) {
this.ean = ean;
}

public String getJan() {
return jan;
}

public void setJan(String jan) {
this.jan = jan;
}

public String getIsbn() {
return isbn;
}

public void setIsbn(String isbn) {
this.isbn = isbn;
}

public String getMpn() {
return mpn;
}

public void setMpn(String mpn) {
this.mpn = mpn;
}

public String getLocation() {
return location;
}

public void setLocation(String location) {
this.location = location;
}

public String getQuantity() {
return quantity;
}

public void setQuantity(String quantity) {
this.quantity = quantity;
}

public String getStockStatus() {
return stockStatus;
}

public void setStockStatus(String stockStatus) {
this.stockStatus = stockStatus;
}

public String getImage() {
return image;
}

public void setImage(String image) {
this.image = image;
}

public String getManufacturerId() {
return manufacturerId;
}

public void setManufacturerId(String manufacturerId) {
this.manufacturerId = manufacturerId;
}

public String getManufacturer() {
return manufacturer;
}

public void setManufacturer(String manufacturer) {
this.manufacturer = manufacturer;
}

public String getPrice() {
return price;
}

public void setPrice(String price) {
this.price = price;
}

public Object getSpecial() {
return special;
}

public void setSpecial(Object special) {
this.special = special;
}

public Object getReward() {
return reward;
}

public void setReward(Object reward) {
this.reward = reward;
}

public String getPoints() {
return points;
}

public void setPoints(String points) {
this.points = points;
}

public String getTaxClassId() {
return taxClassId;
}

public void setTaxClassId(String taxClassId) {
this.taxClassId = taxClassId;
}

public String getDateAvailable() {
return dateAvailable;
}

public void setDateAvailable(String dateAvailable) {
this.dateAvailable = dateAvailable;
}

public String getWeight() {
return weight;
}

public void setWeight(String weight) {
this.weight = weight;
}

public String getWeightClassId() {
return weightClassId;
}

public void setWeightClassId(String weightClassId) {
this.weightClassId = weightClassId;
}

public String getLength() {
return length;
}

public void setLength(String length) {
this.length = length;
}

public String getWidth() {
return width;
}

public void setWidth(String width) {
this.width = width;
}

public String getLengthClassId() {
return lengthClassId;
}

public void setLengthClassId(String lengthClassId) {
this.lengthClassId = lengthClassId;
}

public String getSubtract() {
return subtract;
}

public void setSubtract(String subtract) {
this.subtract = subtract;
}

public Integer getRating() {
return rating;
}

public void setRating(Integer rating) {
this.rating = rating;
}

public Integer getReviews() {
return reviews;
}

public void setReviews(Integer reviews) {
this.reviews = reviews;
}

public String getSortOrder() {
return sortOrder;
}

public void setSortOrder(String sortOrder) {
this.sortOrder = sortOrder;
}

public String getViewed() {
return viewed;
}

public void setViewed(String viewed) {
this.viewed = viewed;
}

}

ошибка- com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was STRING at line 1 column 3 path $[0]

редактирует : Скриншоты: Скриншот Почтальона и Скриншот2 Почтальона

Ответы [ 3 ]

0 голосов
/ 11 июля 2019

Что-то не так с ответом, который вы ожидаете.

Если Json - это то же, что вы разместили, сервис должен быть определен как:

@POST("api/product/getProductbyCategory")
Observable<List<CategoryProductResponse>> getProductListOnCategory(@Query("category_id") String categoryId);

Пожалуйста, убедитесь, что ответ в точности соответствует тому, что вы опубликовали, поскольку похоже, что GSON ожидает Object, а не Array.

EDIT

В вашем POJO есть ошибки:

...
@SerializedName("special")
@Expose
private Object special; // Change this type to String
@SerializedName("reward")
@Expose
private Object reward; // Change this type to String
...
@SerializedName("reviews ") // Remove the whitespace after reviews
@Expose
private Integer reviews;

РЕДАКТИРОВАТЬ 2

Я заметил на скриншоте, что вы не отправляете параметр как Query in postman.

Если вы хотите отправить category_id так же, как в Почтальоне, вам необходимо сделать следующее:

  1. Создать класс для отправки как body:
class ProductsRequest {

    @SerializedName("category_id")
    String categoryId;

    public ProductsRequest(String categoryId) {
        this.categoryId = categoryId;
    }
}

Затем измените ваш сервис, чтобы использовать этот класс в качестве body вызова:

@POST("api/product/getProductbyCategory")
    Observable<List<CategoryProductResponse>> getProductListOnCategory(@Body ProductsRequest request);

Вы отправляете category_id как запрос, когда сервер ожидает body.

0 голосов
/ 11 июля 2019

Ваш код будет работать нормально, если ответ получится так, как вы ожидали.Например, скажем, если у вас есть правильный идентификатор категории, который возвращает товары.Но если идентификатор вашей категории неверен и вы отправляете запрос на сервер, он может не возвращать массив объектов, вместо этого он может возвращать объект с сообщением об ошибке или вообще ничего не возвращать.В этом случае Gson не может прикрепить ответ к List из CategoryProductResponse.Имя CategoryProductResponse не подходит для этого.Лучшее имя будет CategoryProduct или просто Product.

Еще одна вещь, которую я хочу упомянуть, это то, почему вы используете метод POST, чтобы получить это, когда у вас нет значений записи?Параметр Query также можно использовать в запросе GET.

0 голосов
/ 11 июля 2019

используйте это для создания вашего pojo http://www.jsonschema2pojo.org/, потому что вы создали его неправильно.

...