JSON 类型数组的响应主体到 Java 对象

JSON Response Body of type array to Java Object

我正在将类型数组的 JSON 响应转换为 java 对象 class,但是在进行反序列化时出现错误

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $ at com.google.gson.internal.bind.ReflectiveTypeAdapterFactory$Adapter.read(ReflectiveTypeAdapterFactory.java:200)

JSON响应

[
    {
        "name": "Apple iPhone X",
        "price": 700,
        "rating": 4,
        "id": 1
    },
    {
        "name": "Apple Mac Mini",
        "price": 900,
        "rating": 5,
        "id": 2
    },
    {
        "name": "HTC Chacha",
        "price": 200,
        "rating": 3,
        "id": 4
    },
    {
        "name": "Sony Xperia",
        "price": 600,
        "rating": 5,
        "id": 5
    },
    {
        "name": "Samsung Galaxy",
        "price": 400,
        "rating": 2,
        "id": 6
    },
    {
        "name": "LG LED 5600VW",
        "price": 550,
        "rating": 1,
        "id": 7
    },
    {
        "name": "Moto Razor",
        "price": 65000,
        "rating": 4,
        "id": 9
    }
]

Phones.Java(对象 class 模型)

package apiEngine.model.responses;


public class Phones {

public String name;
public Integer price;
public Integer rating;
public Integer id;

public Phones() {
}

public Phones(String name, Integer price, Integer rating, Integer id) {
super();
this.name = name;
this.price = price;
this.rating = rating;
this.id = id;
}

}

正在将 JSON 响应转换为 Java 对象的转换方法

private static Phones phoneResponse;
public void displaylist() {
        RequestSpecification request = RestAssured.given();
        request.header("Content-Type", "application/json").header("x-access-token", token);
        response = request.get("/products");
        phoneResponse = response.getBody().as(Phones.class);
        jsonString = response.asString();
        //System.out.println("list of phone is displayed \n" + phoneResponse);
    }

您正在尝试将 JSON array 作为 object - 您需要将其作为数组获取,不确定它是否适用于 GSON,但通常像这样的东西:

phoneResponse = response.getBody().as(Phones[].class);

应该可以。

其中 phoneResponse 必须是 Phone class 的数组。因此,名称 phones" 可能更合适。

您正在尝试将 JSON 数组转换为对象。试试类似的东西;

final Phones[] phoneResponses = new Gson().fromJson(jsonString, Phones[].class);

此外,我建议您将 Phones class 的名称重构为 Phone,因为它代表单个 phone.