使用GSON解析使用meta和Objects的JSON响应

时间:2013-07-26 17:22:20

标签: java json

我有以下示例响应从URL读取,需要阅读“对象”解析它们并转换为列表

来自服务器的示例响应:

{
    "meta": {
        "limit": 20,
        "next": null,
        "offset": 0,
        "previous": null,
        "total_count": 2
    },
    "objects": [
        {
            "body": "Body of my review",
            "created_by": {
                "first_name": "Josh",
                "id": 2,
                "last_name": "Bothun",
                "username": "josh.bothun.1"
            },
            "id": 1,
            "location": 1,
            "rating": 2,
            "title": "Title of my review"
        },
        {
            "body": "This place is fantastic!",
            "created_by": {
                "first_name": "Josh",
                "id": 1,
                "last_name": "Bothun",
                "username": "josh.bothun.1"
            },
            "id": 2,
            "location": 1,
            "rating": 5,
            "title": "Another review"
        }
    ]
}

我有以下代码,但无法检索对象列表

{           
    Gson GsonObject = new Gson();

String Test = "{\"meta\": {\"limit\": 20,\"next\": null,\"offset\": 0,\"previous\": null,\"total_count\": 2},\"objects\": [ { \"body\": \"Body of my review\",\"created_by\": { \"first_name\": \"Josh\", \"id\": 2, \"last_name\": \"Bothun\",\"username\": \"josh.bothun.1\"}, \"id\": 1,\"location\": 1, \"rating\": 2, \"title\": \"Title of my review\" }, {  \"body\": \"This place is fantastic!\", \"created_by\": { \"first_name\": \"Josh\", \"id\": 1,  \"last_name\": \"Bothun\", \"username\": \"josh.bothun.1\" }, \"id\": 2,\"location\": 1, \"rating\": 5, \"title\": \"Another review\" } ]}";

Type collectionType = new TypeToken<Collection<TabClass>>(){}.getType();
List<TabClass> enums = GsonObject.fromJson(Test, collectionType);

System.out.println(GsonObject.toJson(enums));            

}

class TabClass
{
  private List meta;
  private List objects;
}

1 个答案:

答案 0 :(得分:1)

使用jsonschema2pojo工具为您的json架构提供正确的模型