1

次の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;

    }
}

「アイテム」オブジェクトの内容を知りたいだけなので、呼び出し時に上記のクラスが機能すると想定しました。

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

しかし、エラーが発生します:

スレッド「メイン」での例外 com.google.gson.JsonSyntaxException: java.lang.IllegalStateException: BEGIN_ARRAY が必要でしたが、BEGIN_OBJECT でした

これが何を意味するのかよくわからないので、どこでエラーを探すべきかわかりません.GSONの知識が豊富な人が助けてくれることを願っています.

ありがとう :)

4

2 に答える 2

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 に答える