gpt4 book ai didi

java - 无法获取格式正确的 json 对象

转载 作者:行者123 更新时间:2023-12-01 13:51:10 25 4
gpt4 key购买 nike

假设我从 api 获取一些 json 数组,如下

[{"id":1,"title":"title","description":"description","vote":null,"created_at":"2013-11-12T21:08:10.922Z","updated_at":"2013-11-12T21:08:10.922Z"}]

我想从 URL_Some 网址检索此 json 作为 Some 对象

public class Some implements Serializable {

private String id;
private String title;
private String description;
private String vote;
private String created_at;
private String updated_at;
}//with all getters and setters

.

public List<Some> getSome() throws IOException {
try {
HttpRequest request = execute(HttpRequest.get(URL_Some));
SomeWrapper response = fromJson(request, SomeWrapper.class);
Field[] fields = response.getClass().getDeclaredFields();
for (int i=0; i<fields.length; i++)
{
try {
Log.i("TAG", (String) fields[i].get(response));
} catch (IllegalAccessException e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
Log.i("TAG", fields[i].getName());
}
if (response != null && response.results != null)
return response.results;
return Collections.emptyList();
} catch (HttpRequestException e) {
throw e.getCause();
}
}

SomeWrapper只是

private static class SomeWrapper {

private List<Some> results;
}

问题是我不断收到此消息

java.lang.IllegalStateException: Expected BEGIN_OBJECT but was BEGIN_ARRAY

PS:我用

import com.google.gson.Gson;

import com.google.gson.GsonBuilder;

import com.google.gson.JsonParseException;

最佳答案

你的 json 实际上应该是这样的:

{"results": [{"id":1,"title":"title","description":"description","vote":null,"created_at":"2013-11-12T21:08:10.922Z","updated_at":"2013-11-12T21:08:10.922Z"}]}

Gson 将尝试解析 json 并创建一个 SomeWrapper 对象。仅此一点就告诉 Gson 他将等待这种格式的 json {...}因为他在等待一个物体。然而,您传递了一个数组,这就是为什么它提示期望 BEGIN_OBJECT ( { ) 但得到 BEGIN_ARRAY 而不是 ( [ )。之后,它会期望这个 json 对象有一个 results字段,它将保存一个对象数组。

您可以创建List<Some>然而,无需包装类即可直接使用。为此,请执行以下操作:

Type type= new TypeToken<List<Some>>() {}.getType();
List<Some> someList = new GsonBuilder().create().fromJson(jsonArray, type);

在这种情况下,您可以使用您发布的原始 json 数组。

关于java - 无法获取格式正确的 json 对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19941755/

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