数组类型的json响应主体到java对象

pftdvrlh  于 2021-07-06  发布在  Java
关注(0)|答案(2)|浏览(417)

我正在将array类型的json响应转换为java对象类,但是在进行反序列化时,我得到的错误是
com.google.gson.jsonsyntaxexception:java.lang.illegalstateexception:应为begin\u对象,但在com.google.gson.internal.bind.reflectTypeAdapterFactory$adapter.read的第1行第2列路径$处为begin\u数组(reflectTypeAdapterFactory)。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(对象类模型)

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);
    }
xwbd5t1u

xwbd5t1u1#

您正在尝试转换 JSON 数组到对象。试着做一些类似的事情;

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

或:

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

此外,我建议您重构 Phones 类到 Phone 因为它代表一部手机。

pgvzfuti

pgvzfuti2#

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

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

应该有用。
哪里 phoneResponse 必须是 Phone 班级。因此这个名字 phones “可能更合适。

相关问题