【问题标题】:Converting JSON string to object returns "Expected BEGIN_ARRAY but was STRING" [duplicate]将 JSON 字符串转换为对象返回“预期的 BEGIN_ARRAY 但为字符串”[重复]
【发布时间】:2019-03-04 13:14:21
【问题描述】:

我有一个 JSON 响应从我的服务器返回,格式为:

[
    {
        "id": "one",
        "values": {
            "name": "John",
        }
    },
    {
        "id": "two",
        "values": {
            "name": "Bob",
        }
    }
]

这是我设置的课程:

public class TestClass implements Serializable {

    @SerializedName("id")
    private String id;

    @SerializedName("values")
    private List<String> values;

    public String getId() {
        return id;
    }

    public void setId(String id) {
        this.id = id;
    }

    public List<String> getValues() {
        return values;
    }

    public void setValues(List<String> values) {
        this.values = values;
    }
}

这是我将 JSON 解析为对象列表的代码:

String response = serverResponseHere;
Gson gson = new Gson();
String json = gson.toJson(response);

Type collectionType = new TypeToken<List<TestClass>>(){}.getType();
List<TestClass> values = gson.fromJson(json, collectionType);

但是,我收到以下错误:

com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: 应为 BEGIN_ARRAY 但为 STRING

这是怎么回事?

【问题讨论】:

  • 根据您的值,它只是对象数组而不是列表字符串
  • 将对象用作列表导致错误。这是正确的: = Type collectionType = new TypeToken(){}.getType(); .你儿子也错了

标签: java android json gson


【解决方案1】:

您正在获取 JSON 响应内容

String response = serverResponseHere;

并将其转换为 JSON

Gson gson = new Gson();
String json = gson.toJson(response);

这会生成一个包含您的内容的 JSON 字符串。看起来像

"[\n    {\n        \"id\": \"one\",\n        \"values\": {\n            \"name\": \"John\",\n        }\n    },\n    {\n        \"id\": \"two\",\n        \"values\": {\n            \"name\": \"Bob\",\n        }\n    }\n]\n"

当您尝试将其反序列化为 List&lt;TestClass&gt; 时,它显然会失败,因为它是 JSON 字符串而不是 JSON 数组。

在反序列化之前不要将您的内容序列化为 JSON,它已经是 JSON。


其他人已经提到这一点,您的 values 字段与您的 JSON 内容不匹配。请参阅此处了解如何解决此问题:

【讨论】:

  • 这应该是公认的答案。
【解决方案2】:

从以下位置更改您的服务器响应 json:

[
    {
        "id": "one",
        "values": {
            "name": "John",
        }
    },
    {
        "id": "two",
        "values": {
            "name": "Bob",
        }
    }
]

收件人:

[
    {
        "id": "one",
        "values": [
            {"name": "John"}
        ]
    },
    {
        "id": "two",
        "values": [
            {"name": "Bob"}
        ]
    }
]

【讨论】:

  • 还是不行,因为{"name": "John"} 不是字符串
  • 这也不应该是因为它需要是 json 数组中的 json 对象。错误是它在预期数组的位置获取字符串。
  • List&lt;String&gt; 期望类似于 ["John", "Bob"]
猜你喜欢
  • 1970-01-01
  • 2015-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-09-19
  • 1970-01-01
  • 2014-07-06
  • 2019-09-27
相关资源
最近更新 更多