簡體   English   中英

使用GSON時發生IllegalStateException

[英]IllegalStateException when using GSON

我試圖讀取以下JSON文件:

{ "rss" : {
     "@attributes" : {"version" : "2.0" },
      "channel" : { 
          "description" : "Channel Description",
          "image" : { 
              "link" : "imglink",
              "title" : "imgtitle",
              "url" : "imgurl"
            },

          "item" : {
              "dc_format" : "text",
              "dc_identifier" : "link",
              "dc_language" : "en-gb",
              "description" : "Description Here",
              "guid" : "link2",
              "link" : "link3",
              "pubDate" : "today",
              "title" : "Title Here"
            },

          "link" : "channel link",
          "title" : "channel title"
        }
    } 
}

進入這個對象:

public class RSSWrapper{
    public RSS rss;

    public class RSS{
        public Channel channel;
    }

    public class Channel{
        public List<Item> item;

    }
    public class Item{
        String description;//Main Content
        String dc_identifier;//Link
        String pubDate;
        String title;

    }
}

我只對知道“ item”對象中的內容感興趣,因此我認為上述類在調用時會起作用:

Gson gson = new Gson();
RSSWrapper wrapper = gson.fromJson(JSON_STRING, RSSWrapper.class);

但我收到一個錯誤:

線程“ main”中的異常com.google.gson.JsonSyntaxException:java.lang.IllegalStateException:預期為BEGIN_ARRAY,但為BEGIN_OBJECT

我真的不知道這意味着什么,所以我不知道在哪里尋找錯誤,希望對GSON有更好了解的人可以幫助我?

謝謝 :)

您的JSON字符串和RSSWrapper類不兼容:當JSON字符串包含一項時, Channel希望具有List<Item> 您必須將Channel修改為:

public class Channel{
    public Item item;

}

或JSON為:

"item" : [{
    "dc_format" : "text",
    "dc_identifier" : "link",
    "dc_language" : "en-gb",
    "description" : "Description Here",
    "guid" : "link2",
    "link" : "link3",
    "pubDate" : "today",
    "title" : "Title Here"
}],

表示它是一個有一個元素的數組。

如果您控制JSON輸入的外觀,最好將item更改為JSON數組

"item" : [{
    "dc_format" : "text",
    "dc_identifier" : "link",
    "dc_language" : "en-gb",
    "description" : "Description Here",
    "guid" : "link2",
    "link" : "link3",
    "pubDate" : "today",
    "title" : "Title Here"
}]

如果您不這樣做,並且希望程序能夠使用相同的RSSWrapper類處理item數組或對象,那么請執行以下RSSWrapper 這是適合您的程序化解決方案。

JSONObject jsonRoot = new JSONObject(JSON_STRING);
JSONObject channel = jsonRoot.getJSONObject("rss").getJSONObject("channel");

System.out.println(channel);
if (channel.optJSONArray("item") == null) {
    channel.put("item", new JSONArray().put(channel.getJSONObject("item")));
    System.out.println(channel);
}

Gson gson = new Gson();
RSSWrapper wrapper = gson.fromJson(jsonRoot.toString(), RSSWrapper.class);

System.out.println(wrapper.rss.channel.item.get(0).title); // Title Here

使用Java org.json解析器,代碼只需將JSONObject包裝到數組中即可替換它。 如果item已經是JSONArrayJSON_STRING保持JSON_STRING不變。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM