gpt4 book ai didi

android - 使用 gson 解析 JSON 对象

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

我正在尝试像这样解析 JSON:

{"response":[123123, 1231231, 123124, 124124, 111111, 12314]}

有了GSON,制作

Gson gson = new GsonBuilder().create();
int[] friends = new Gson().fromJson(answer, int[].class);
System.out.print(friends[0]);

但是得到 Error Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

如何解析数组中的数字?

最佳答案

您首先要创建一个模型类,GSON 可以将您的 json 绑定(bind)到:

public class ResponseModel {

private List<Integer> response = new ArrayList<Integer>();

public List<Integer> getResponse() {
return response;
}

@Override
public String toString() {
return "ResponseModel [response=" + response + "]";
}
}

然后就可以调用了

Gson gson = new Gson();
ResponseModel responseModel = gson.fromJson("{\"response\":[123123, 1231231, 123124, 124124, 111111, 12314]}",
ResponseModel.class);
List <Integer> responses = responseModel.getResponse();
// ... do something with the int list

关于android - 使用 gson 解析 JSON 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21503158/

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