gpt4 book ai didi

安卓 JSON 错误 "Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2"

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

我正在从网络服务获取 JSON 数据,示例数据如下:

[
{
"SectionId": 1,
"SectionName": "Android"
}
]

当我尝试转换它时,它会抛出一个错误,我是这样做的:

Data data = new Gson().fromJson(jsonDataFromWebService, Data.class);

我的类(class)是:

class Section
{
public int SectionId;
public String SectionName;
}

class Data {
public List<Section> sections;
}

LogCat 说:

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

最佳答案

您正在尝试从 JSONArray 创建一个非 Array(Collection) 对象。错误非常明显:GSON 期待对象的开头,但却找到了数组的开头。

查看下面的文档页面,了解如何使用 GSON 处理数组和集合类型

https://sites.google.com/site/gson/gson-user-guide#TOC-Collections-Examples

来自文档:

Array Examples

Gson gson = new Gson(); int[] ints = {1, 2, 3, 4, 5}; String[] strings = {"abc", "def", "ghi"};

(Serialization) gson.toJson(ints); ==> prints [1,2,3,4,5] gson.toJson(strings); ==> prints ["abc", "def", "ghi"]

(Deserialization) int[] ints2 = gson.fromJson("[1,2,3,4,5]", int[].class); ==> ints2 will be same as ints

We also support multi-dimensional arrays, with arbitrarily complex element types Collections Examples

Gson gson = new Gson(); Collection ints = Lists.immutableList(1,2,3,4,5);

(Serialization) String json = gson.toJson(ints); ==> json is [1,2,3,4,5]

(Deserialization) Type collectionType = new TypeToken>(){}.getType(); Collection ints2 = gson.fromJson(json, collectionType); ints2 is same as ints

Fairly hideous: note how we define the type of collection Unfortunately, no way to get around this in Java

Collections Limitations

Can serialize collection of arbitrary objects but can not deserialize from it Because there is no way for the user to indicate the type of the resulting object While deserializing, Collection must be of a specific generic type All of this makes sense, and is rarely a problem w> hen following good Java coding practices

关于安卓 JSON 错误 "Expected BEGIN_OBJECT but was BEGIN_ARRAY at line 1 column 2",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9441932/

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