1

im trying to read the following JSON file:

{ "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"
        }
    } 
}

Into this object:

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;

    }
}

Im only interested in knowing what's in the "item" object so i assumed the above class would work when calling:

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

but im getting an error:

Exception in thread "main" com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: Expected BEGIN_ARRAY but was BEGIN_OBJECT

I don't really know what this means so I don't know where to look for the error, hopefully someone with a better knowledge of GSON can help me?

Thanks :)

4

2 回答 2

1

您的 JSON 字符串和RSSWrapper类不兼容:Channel预计List<Item>JSON 字符串会包含一个项目。您必须修改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"
}],

表示它是一个包含一个元素的数组。

于 2013-08-24T16:27:34.053 回答
1

如果您控制 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"
}]

如果您不这样做并且希望您的程序能够处理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通过将其包装到一个数组中来简单地替换 。如果JSON_STRING已经itemJSONArray.

于 2013-08-24T16:52:30.407 回答