gpt4 book ai didi

java - 改造将对象数组转换为 GSON 错误

转载 作者:塔克拉玛干 更新时间:2023-11-02 09:08:01 26 4
gpt4 key购买 nike

我正在使用 Retrofit 发出返回对象数组的 HTTP 请求,但出现以下错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

返回的响应应该是这样的:

[ {key1: "value1", key2: "value2"}, {key1: "value1", key2: "value2"}, ... ]

我有以下类,用于序列化数据:

public class data {
private List<element> dataList;

public List<element> getElements() {
return dataList;
}

public class element {
@SerializedName("key1")
private String key1;

@SerializedName("key2")
private String key2;

// Getters and Setters
}
}

如果您有任何想法,请告诉我。谢谢

最佳答案

错误实际上是在我实现 Retrofit Callback 时。在这种情况下,当它应该期待一个数组时,我的实现期待一个对象。感谢大家的帮助。

之前

//*****MyData*****//
public class MyData {
private List<Data> dataList;

public List<Data> getElements() {
return dataList;
}

public class Data {
@SerializedName("key1")
private String key1;

@SerializedName("key2")
private String key2;

// Getters and Setters
}
}

//*****Callback Implementation*****//
public class MyDataCallback extends Callback {
public MyDataCallback(MyDataCallbackListener<MyData> myDataCallbackListener) {
super(myDataCallbackListener);
}

@Override
public void success(MyData data, Response response) {
if (myDataCallbackListener != null) {
myDataCallbackListener.onCallbackComplete(true, response, MyDataCallback.CALLBACK_SUCCESS_MESSAGE, data);
}
}
}

之后

//*****Data*****//
public class Data {
@SerializedName("key1")
private String key1;

@SerializedName("key2")
private String key2;

// Getters and Setters
}

//*****Callback Implementation*****//
public class MyDataCallback extends Callback {
public MyDataCallback(MyDataCallbackListener<List<Data>> myDataCallbackListener) {
super(myDataCallbackListener);
}

@Override
public void success(List<Data> data, Response response) {
if (myDataCallbackListener != null) {
myDataCallbackListener.onCallbackComplete(true, response, MyDataCallback.CALLBACK_SUCCESS_MESSAGE, data);
}
}
}

关于java - 改造将对象数组转换为 GSON 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25817604/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com