gpt4 book ai didi

android - 无法在 retrofit 2.0 中解析具有两种不同数据类型的 json

转载 作者:行者123 更新时间:2023-11-29 00:04:47 26 4
gpt4 key购买 nike

我正在尝试将下面的 json 解析为一个名为 AlbumResponse 的对象,该对象内部还有另外两个对象,AlbumPaginationInfo。改造2.0版本

[
{
"id": "6",
"name": "King Stays King",
"artist_name":"Timbaland",
"image":""
},
{
"id": "7",
"name": "East Atlanta Santa 2",
"artist_name":"Gucci Mane",
"image":""
},
{
"id": "8",
"name": "The cuban connect",
"artist_name":"Phophit",
"image":""
},
{
"id": "9",
"name": "Shmoney Keeps",
"artist_name":"Calling",
"image":""
},
{
"id": "10",
"name": "Cabin Fever 3",
"artist_name":"Wiz khalifa",
"image":""
}
],
{
"nextPage": "http://private-ede172-mymixtapez1.apiary-mock.com/features/page_3/",
"itemsTotal": 10,
"page": 2,
"pagerMax": 2
}

相册类

public class Album {
long id;
String name;
@SerializedName("artist_name")
String artistName;
String image;
}

PaginationInfo 类

public class PaginationInfo {
int page;
int pagerMax;
int nextPage;
int itemsTotal;
}

AlbumResponse,里面有上面两个类,Album是一个List

public class AlbumResponse {
public List<Album> albums;
public PaginationInfo paginationInfo;
}

请求

Call<AlbumResponse> responseCall = albumService.features();
responseCall.enqueue(new Callback<AlbumResponse>() {
@Override
public void onResponse(Response<AlbumResponse> response, Retrofit retrofit) {
if(response.isSuccess()) {
AlbumResponse albumResponse = response.body();
PaginationInfo paginationInfo = albumResponse.getPaginationInfo();

}
System.out.println();
}

@Override
public void onFailure(Throwable t) {
System.out.println(t.getMessage());
}
});

界面

public interface AlbumService {
@GET("/features/")
Call<AlbumResponse> features();
}

问题是我得到一个 Throwable 包含:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2 path $`

拜托,有人可以帮助我吗,我在 stackoverflow 中没有找到任何答案。谢谢。

最佳答案

错误提示:解析器需要一个 JSON 对象,但它读取的是一个 JSON 数组。要修复它(如果您控制服务器),您应该将 JSON 字符串更改为如下内容:

{
"albums" : [
{
"id": "6",
"name": "King Stays King",
"artist_name":"Timbaland",
"image":""
},
{
"id": "7",
"name": "East Atlanta Santa 2",
"artist_name":"Gucci Mane",
"image":""
},
{
"id": "8",
"name": "The cuban connect",
"artist_name":"Phophit",
"image":""
},
{
"id": "9",
"name": "Shmoney Keeps",
"artist_name":"Calling",
"image":""
},
{
"id": "10",
"name": "Cabin Fever 3",
"artist_name":"Wiz khalifa",
"image":""
}
],
"paginationInfo" : {
"nextPage": "http://private-ede172-mymixtapez1.apiary-mock.com/features/page_3/",
"itemsTotal": 10,
"page": 2,
"pagerMax": 2
}
}

现在它是一个 JSON 对象并且符合您的 Java 类。

如果您不能在后端更改 JSON,我会将其作为行响应并使用 GSON 或手动分别解析 albums ArrayPaginationInfo

顺便说一句。您必须将 PaginationInfo 类中的 nextPage 类型从 int 更改为 String

关于android - 无法在 retrofit 2.0 中解析具有两种不同数据类型的 json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34640928/

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