【问题标题】:Expected BEGIN_ARRAY but was STRING应为 BEGIN_ARRAY,但为 STRING
【发布时间】:2014-11-05 05:58:53
【问题描述】:

我正在尝试使用此代码从 URL 解析 Json 数组。

public class Main {
static class Item {
    @SerializedName("id")
    public String id;

    @SerializedName("name")
    public String name;

    @SerializedName("timelimitstart")
    public String timelimitstart;

    @SerializedName("timelimitend")
    public String timelimitend;

    @SerializedName("esttime")
    public String esttime;

    @SerializedName("location")
    public String location;

    @SerializedName("description")
    public String description;
}

private static String readUrl(String urlString) throws Exception {
    BufferedReader reader = null;
    try {
        URL url = new URL(urlString);
        reader = new BufferedReader(new InputStreamReader(url.openStream()));
        StringBuffer buffer = new StringBuffer();
        int read;
        char[] chars = new char[1024];
        while ((read = reader.read(chars)) != -1)
            buffer.append(chars, 0, read);

        return buffer.toString();
    } finally {
        if (reader != null)
            reader.close();
    }
}

public static void main(String[] args) throws Exception {
    Gson gson = new Gson();

    String fromURL = readUrl("http://ec2-54-69-156-10.us-west-2.compute.amazonaws.com/getactivities.php");
    String nonURL = "[{\"id\":\"1\",\"name\":\"Mine raamatukokku\",\"timelimitstart\":\"\",\"timelimitend\":\"\",\"esttime\":\"00:00:00\",\"location\":\"\",\"description\":\"Mine Ƶpi!\"},{\"id\":\"1\",\"name\":\"Mine raamatukokku\",\"timelimitstart\":\"\",\"timelimitend\":\"\",\"esttime\":\"00:00:00\",\"location\":\"\",\"description\":\"Mine Ƶpi!\"}]";

    Item[] data = gson.fromJson(nonURL, Item[].class);

}

}

它适用于非 URL 输入并解析得很好,但使用 fromURL 输入时它会显示“预期 BEGIN_ARRAY 但为 STRING”。

我认为 fromURL 它在 [ 前面有 \" ,这就是它有问题的原因,但我不知道如何解决它。

【问题讨论】:

  • 如果我请求该 URL,我会在文件内容中得到一个 <meta charset="UTF-8">。你可能想跳过那个。

标签: java json gson


【解决方案1】:

您从 url 获得的响应在其第一行有 <meta charset="UTF-8">(您可以通过直接从浏览器浏览 url 并查看其源代码来查看它):

要使其成为有效的 json,您可以删除该行:

String fromURL = readUrl("http://ec2-54-69-156-10.us-west-2.compute.amazonaws.com/getactivities.php");

fromURL = fromURL.replace("<meta charset=\"UTF-8\">", "");
Item[] data = gson.fromJson(fromURL, Item[].class);

编辑: http://ec2-54-69-156-10.us-west-2.compute.amazonaws.com/getactivities.php的当前回复:

<meta charset="UTF-8">
[{"id":"1","name":"Mine raamatukokku","timelimitstart":"","timelimitend":"","esttime":"00:00:00","location":"","description":"Mine õpi!"},{"id":"2","name":"Mine jooksma","timelimitstart":"","timelimitend":"","esttime":"00:00:00","location":"","description":"Sport on hea"},{"id":"3","name":"Tee uinak","timelimitstart":"","timelimitend":"","esttime":"00:00:00","location":"","description":"1 tund"}]

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-01-15
    • 2015-11-30
    • 2013-05-10
    • 1970-01-01
    • 2020-11-30
    • 2019-09-22
    • 1970-01-01
    相关资源
    最近更新 更多