gpt4 book ai didi

android - 如何使用 Retrofit 获取 JSON 响应

转载 作者:行者123 更新时间:2023-11-29 01:18:41 24 4
gpt4 key购买 nike

{
"records": [
{
"id": "744",
"categoryname": "Floor Tiles",
"photo": "",
"width": "0",
"height": "0",
"secondlevelcategory": [
{
"id": "833",
"categoryname": "Digital Vitrified Tiles",
"photo": "http://image.com",
"width": "1031",
"height": "700"
}
]
},
{
"id": "744",
"categoryname": "Floor Tiles",
"photo": "",
"width": "0",
"height": "0",
"secondlevelcategory": [
{
"id": "833",
"categoryname": "Digital Vitrified Tiles",
"photo": "http://image.com",
"width": "1031",
"height": "700"
}
]
}
] }

我如何将此 Json 响应转换为 Retrofit bean 我收到 Gson 错误,如 Use JsonReader.setLenient(true) to accept malformed JSON at line 1 column 1 path $

private void callCategoryApi() {
Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd'T'HH:mm:ssZ").create();
Retrofit retrofit = new Retrofit.Builder()
.baseUrl(GithubUserAPI.CATEGORY_API)
.addConverterFactory(GsonConverterFactory.create(gson))
.build();

GithubUserAPI githubUserAPI = retrofit.create(GithubUserAPI.class);
Call<List<CatResponseData>> call = githubUserAPI.getCategory(Utils.key);
call.enqueue(this);

}

@Override
public void onResponse(Call<List<CatResponseData>> call, Response<List<CatResponseData>> response) {
int code = response.code();
if (code == 200) {
List<CatResponseData> res = response.body();
for(CatResponseData resDat : res){
System.out.println("=== Response : " + resDat.getCategoryname());
}
}else{
Toast.makeText(this, "Did not work: " + String.valueOf(code), Toast.LENGTH_LONG).show();
}
}

@Override
public void onFailure(Call<List<CatResponseData>> call, Throwable t) {
System.out.println("=== Error : " + t.getMessage());
}

api调用是

@POST("/apikey/{apikey}")
Call<List<CatResponseData>> getCategory(@Path("apikey") String user);

字符串 CATEGORY_API = "https://api.callingservice.com ";

请帮我解决这个问题我如何将 Json 响应转换为 Bean 和我的 Bean 类是这样的

public class CategoryBean {
List<CatResponseData> responseData = new ArrayList<CatResponseData>(); } class CatResponseData {
String id;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getCategoryname() {
return categoryname;
}
public void setCategoryname(String categoryname) {
this.categoryname = categoryname;
}
String categoryname; }

最佳答案

这应该是您赋予 Retrofit 的类。不是 beans 列表,因为它们被封装在一个对象中。

 public class CategoryResponse {
@SerializedName("records")
List<CategoryBean> responseData;

public List<CatResponseData> getResponseData() {
return responseData;
}
}

关于android - 如何使用 Retrofit 获取 JSON 响应,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38146854/

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