解密JSON响应googles主题api

时间:2013-07-24 19:07:02

标签: java json google-api freebase mql

我正在使用goggle的search api来获取主题id,用于从主题api获取JSON响应。返回的响应看起来像这样

{
"id":"/m/01d5g",
"property":{
    "/amusement_parks/ride_theme/rides":{...},
    "/award/ranked_item/appears_in_ranked_lists":{...},
    "/book/book_character/appears_in_book":{
            "valuetype":"object",
            "values":[
                {
                    "text":"Inferno",
                    "lang":"en",
                    "id":"/m/0g5qs3",
                    "creator":"/user/duck1123",
                    "timestamp":"2010-02-11T04:00:59.000Z"
                },
                {
                    "text":"Batman: Year One",
                    "lang":"en",
                    "id":"/m/0hzz_1h",
                    "creator":"/user/anasay",
                    "timestamp":"2012-01-25T11:05:03.000Z"
                },
                {
                    "text":"Batman: The Dark Knight Returns",
                    "lang":"en",
                    "id":"/m/0hzz_sb",
                    "creator":"/user/anasay",
                    "timestamp":"2012-01-25T11:22:17.001Z"
                },
                {
                    "text":"Batman: Son of the Demon",
                    "lang":"en",
                    "id":"/m/071l77",
                    "creator":"/user/wikimapper",
                    "timestamp":"2013-07-11T15:20:32.000Z"
                },
                {
                    "text":"Joker",
                    "lang":"en",
                    "id":"/m/04zxvhs",
                    "creator":"/user/wikimapper",
                    "timestamp":"2013-07-11T16:58:37.000Z"
                },
                {
                    "text":"Arkham Asylum: A Serious House on Serious Earth",
                    "lang":"en",
                    "id":"/m/0b7hyw",
                    "creator":"/user/wikimapper",
                    "timestamp":"2013-07-11T19:26:54.000Z"
                }
            ],
            "count":6.0
    },
    "/book/book_subject/works":{...},
    "/comic_books/comic_book_character/cover_appearances":{...},
    ... 
}
}

我想解读这个,以便我可以获得相关信息,例如“/ book / book_character / appear_in_book”本身是一个响应的属性,只需要我想要的值是“文本“和”id“例如“text”:“蝙蝠侠:第一年”“id”:“/ m / 0hzz_1h”。 由于响应没有固定属性,并且可能根据响应id而变化。我如何在java类中转换此JSON响应,我可以将“/ book / book_character / appear_in_book”存储为一个序列化类,并包含 id text 等值的集合和 appear_in_book 作为类的名称变量。

我考虑过GSON来做这件事。由于属性名称不是常量,我不能用它来将JSON转换为Java对象。目前我通过硬编码迭代每个属性并在java变量中填充它们。

如果有人可以提供有效的方法,我会很感激帮助。

1 个答案:

答案 0 :(得分:1)

您可以使用Java中的反射动态执行此操作,但这是Java的高级功能,它可能会使您的代码更加复杂。

请参阅:Dynamically create an object in java from a class name and set class fields by using a List with data

更简单的替代方法是将JSON解析为一堆嵌套的地图和列表,就像在JSON数据中给出的那样。

请参阅:How to parse JSON in Java