gpt4 book ai didi

java - 如何在 Android 中通过改造访问 JSON 响应中的特定值?

转载 作者:行者123 更新时间:2023-11-29 23:10:00 24 4
gpt4 key购买 nike

我有一个来自 marvel api 的 JSON 响应,我可以从中获取第一级的版权信息,这是对服务的响应:

{
"code": 200,
"status": "Ok",
"copyright": "© 2019 MARVEL",
"attributionText": "Data provided by Marvel. © 2019 MARVEL",
"attributionHTML": "<a href=\"http://marvel.com\">Data provided by Marvel. © 2019 MARVEL</a>",
"etag": "a1d8666dc86abda3bd2edf99d09446da82626c4b",
"data": {
"offset": 0,
"limit": 20,
"total": 1,
"count": 1,
"results": [
{
"id": 1009664,
"name": "Thor",
"description": "As the Norse God of thunder and lightning, Thor wields one of the greatest weapons ever made, the enchanted hammer Mjolnir. While others have described Thor as an over-muscled, oafish imbecile, he's quite smart and compassionate. He's self-assured, and he would never, ever stop fighting for a worthwhile cause.",
.
.
.
}

我有这样的 getter 和 setter:

private int id;
private String name;
private String description;
private String thumbnail;

private String copyright;

public Heroe() {}


public Heroe(String copyright, int id, String name, String description, String thumbnail) {
this.copyright = copyright;
this.id = id;
this.name = name;
this.description = description;
this.thumbnail = thumbnail;
}

但我想从数据中得到结果。要获取 ID、名称和描述,这是我的代码:

Android response service from MARVEL

最佳答案

由于 json 响应有一个子节点尝试创建一个自定义响应,如

HeroResponse.java

class HeroResponse {
private int code;
private String status;
//.. other variables
@SerializedName("data")
private Hero data

//.. Getter and setter
}

Hero.java

class Hero {
private int offset;
private int limit;
//.. other variables
@SerializedName("results")
private HeroDetail results

//.. Getter and setter
}

HeroDetail.java

class HeroDetail {
private int id;
private String name;
private String description

//.. Getter and setter
}

然后在你的 retrofit 电话上

heroeCall.enqueue(
//..
public void onResponse(Call<HeroResponse> call, Response<HeroResponse> response) {
HeroResponse resp = response.body();
resp.copyright
resp.data.offset
resp.data.results.id
}
)

另外,如果您想使用注释 SerializedName,请不要忘记在您的应用程序 build.gradle 中实现 'com.google.code.gson:gson:2.8.5'

希望这会有所帮助。

关于java - 如何在 Android 中通过改造访问 JSON 响应中的特定值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56122058/

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