使用Java / Jackson解析JSON

时间:2011-12-05 16:32:45

标签: java json jackson gson

我有一个小型测试应用程序,我用Java编写来解析Reddit API中的一些JSON。我想要解析的一些示例JSON将是这样的:

[
{
    "kind": "Listing",
    "data": {
        "modhash": "1jq62oyvwe15aaba7eb18b0b4363b567a00750766351e03dcc",
        "children": [
            {
                "kind": "t3",
                "data": {
                    "domain": "businessinsider.com",
                    "media_embed": {},
                    "levenshtein": null,
                    "subreddit": "Android",
                    "selftext_html": null,
                    "selftext": "",
                    "likes": null,
                    "saved": false,
                    "id": "n17u2",
                    "clicked": false,
                    "title": "CONFESSION OF A NON-APPLE-FANBOY: Even If The Samsung Galaxy Nexus Is Better, I'm Still Buying An iPhone",
                    "media": null,
                    "score": 0,
                    "over_18": false,
                    "hidden": false,
                    "thumbnail": "http://e.thumbs.redditmedia.com/sL0dCwGAvWqnY_sd.jpg",
                    "subreddit_id": "t5_2qlqh",
                    "author_flair_css_class": null,
                    "downs": 2,
                    "is_self": false,
                    "permalink": "/r/Android/comments/n17u2/confession_of_a_nonapplefanboy_even_if_the/",
                    "name": "t3_n17u2",
                    "created": 1323127132,
                    "url": "http://www.businessinsider.com/apple-iphone-versus-samsung-galaxy-nexus-2011-12",
                    "author_flair_text": null,
                    "author": "FormulaT",
                    "created_utc": 1323101932,
                    "num_comments": 0,
                    "ups": 1
                }
            }
        ],
        "after": null,
        "before": null
    }
},
{
    "kind": "Listing",
    "data": {
        "modhash": "1jq62oyvwe15aaba7eb18b0b4363b567a00750766351e03dcc",
        "children": [],
        "after": null,
        "before": null
    }
}
]

我想要完成的是从这个JSON中获取一些值,例如标题和作者。我正在使用Jackson处理JSON,我使用的代码如下所示:

URLConnection conn = redditURL.openConnection();
BufferedReader buf = new BufferedReader(new InputStreamReader(conn.getInputStream()));

ObjectMapper mapper = new ObjectMapper();
RedditComment comment = mapper.readValue(buf, RedditComment.class);
Iterator itr = comment.getData().getChildren().listIterator();

我使用JSONGen网站(http://jsongen.byingtondesign.com/)创建了RedditComment和其他所需的类。但是,当从BufferedReader解析JSON时,Jackson抛出了这个异常:

org.codehaus.jackson.map.JsonMappingException: Can not deserialize instance of com.test.RedditAPI.RedditComment out of START_ARRAY token
at [Source: java.io.BufferedReader@3ebfbbe3; line: 1, column: 1]
at org.codehaus.jackson.map.JsonMappingException.from(JsonMappingException.java:163)
at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:219)
at org.codehaus.jackson.map.deser.StdDeserializationContext.mappingException(StdDeserializationContext.java:212)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserializeFromArray(BeanDeserializer.java:869)
at org.codehaus.jackson.map.deser.BeanDeserializer.deserialize(BeanDeserializer.java:597)
at org.codehaus.jackson.map.ObjectMapper._readMapAndClose(ObjectMapper.java:2723)
at org.codehaus.jackson.map.ObjectMapper.readValue(ObjectMapper.java:1877)
at com.test.RedditAPI.main.returnRedditComment(Main.java:17)

有没有人有任何想法?我现在已经摸不着头几个小时了。

编辑:感谢@Chin Boon和@Chris,我想出了以下内容(切换到GSON后):

Gson gson = new Gson();
List<RedditComment> comment = gson.fromJson(buf, new TypeToken<List<RedditComment>>() {}.getType());
List<RedditChildren> children = comment.get(1).getData().getChildren();
System.out.println(children.get(1).getData().getAuthor());

但会抛出以下异常:

java.lang.ClassCastException: java.util.LinkedHashMap cannot be cast to com.test.RedditAPI.RedditChildren

道歉,如果我是一个麻烦,我看了看API并没有任何LinkedHashMaps的参考,所以我不知道它为什么会出现在这里。

2 个答案:

答案 0 :(得分:5)

问题是响应是一系列条目。尝试:

List<RedditComment> comment = mapper.readValue(buf,new TypeReference<List<RedditComment>>(){});

答案 1 :(得分:1)

如果你还没有投入太多时间进入杰克逊,我可以建议你看看应该让你开始的GSON,here is a tutorial

Google GSON API将您的JSON字符串映射到域对象。

http://java.sg/parsing-a-json-string-into-an-object-with-gson-easily/

此外,您可以使用JSON parser查看您的JSON。