问题描述
我正在将类型数组的JSON响应转换为java Object类,但是在进行反序列化时却收到错误消息
com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:预期为BEGIN_OBJECT,但在第1行第2列路径处为BEGIN_ARRAY 位于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,"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,"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);
}
解决方法
您正在尝试将JSON
数组转换为对象。尝试类似的东西;
final Phones[] phoneResponses = response.getBody().as(Phones[].class);
或者:
final Phones[] phoneResponses = new Gson().fromJson(jsonString,Phones[].class);
此外,我建议您将Phones
类的名称重构为Phone
,因为它代表单个电话。
您正在尝试将JSON array
用作object
-您需要将其作为数组获取,不确定它是否适用于GSON
,但通常是这样的:
phoneResponse = response.getBody().as(Phones[].class);
应该工作。
phoneResponse
必须是Phone
类的数组。因此,phones
这个名称可能更合适。