我正在学习通过 Retrofit 在 Android 中进行 API 调用,但由于使用 Retrofit 库将 JSON 转换为 java 对象而陷入困境。我已经详细解释了这个问题如下。如果有人能提供帮助,我将不胜感激。
我有以下 JSON 作为来 self 的 API 的响应 ---
[
{
"key1": "value1",
"key2": "value2",
"key3": "["v1", "v2", "v3"]"
}
]
在android环境中,我使用retrofit来调用API。 我制作了以下 POJO ----
public class apiResponsePOJO implements Serializable {
@SerializedName("key1")
@Expose
private String key1;
@SerializedName("key2")
@Expose
private String key2;
@SerializedName("key3")
@Expose
private List<String> key3;
// I have created the getter and setter methods for all the three attributes.
}
APIInterface 类包含以下 GET 方法定义 --
@GET("attribute/")
Call<apiResponsePojo> getAttribute(@Query("attributeID") Integer attributeID);
我正在 fragment 类之一中调用 API 接口(interface),如下所示 --
APIInterface apiInterface = APIClient.getClient(url).create(APIInterface.class);
getAttributeDetails(attributeID);
getAttributeDetails方法的定义如下 --
public void getAttributeDetails(int attributeID) {
Call<apiResponsePOJO> call = apiInterface.getAttribute(attributeID);
call.enqueue(new Callback<apiResponsePOJO>() {
@Override
public void onResponse(Call<apiResponsePOJO> call, Response<apiResponsePOJO> response) {
apiResponseDetails = response.body();
Log.e("Server", "response = " + apiResponseDetails.getValue1());
}
@Override
public void onFailure(Call<apiResponsePOJO> call, Throwable t) {
Log.e("Server", t.getMessage());
// t.printStackTrace();
}
});
}
我收到的错误是:第 15 行第 20 列路径 $.key3 处的对象未终止
有人可以向我解释一下为什么会发生这种情况吗?
最佳答案
您的回复格式错误,key3 是 JSONArray,因此没有引号
应该是:
[
{
“键1”:“值1”,
“键2”:“值2”,
“key3”:[“v1”,“v2”,“v3”]
}
]
关于java - 当 json 中的键之一包含值列表时,使用 Retrofit 将 JSON 键值对转换为 Java 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60480871/