使用GSON解析JSON数组

时间:2013-08-24 18:17:47

标签: java arrays json gson

我有一个像这样的JSON文件:

[
    {
        "number": "3",
        "title": "hello_world",
    }, {
        "number": "2",
        "title": "hello_world",
    }
]

在文件有根元素之前我会使用:

Wrapper w = gson.fromJson(JSONSTRING, Wrapper.class);

代码,但我想不出如何编写Wrapper类,因为根元素是一个数组。

我尝试过使用:

Wrapper[] wrapper = gson.fromJson(jsonLine, Wrapper[].class);

with:

public class Wrapper{

    String number;
    String title;

}

但是没有运气。我怎么能用这种方法读到这个?

P.S我可以使用:

JsonArray entries = (JsonArray) new JsonParser().parse(jsonLine);
String title = ((JsonObject)entries.get(0)).get("title");

但我更愿意知道如何使用这两种方法(如果可能的话)。

4 个答案:

答案 0 :(得分:105)

问题是由数组中每个 JSON对象末尾的逗号引起的(在每个"title": "..", }的末尾< - 请看逗号?)。如果您将其删除并将数据更改为

[
    {
        "number": "3",
        "title": "hello_world"
    }, {
        "number": "2",
        "title": "hello_world"
    }
]

Wrapper[] data = gson.fromJson(jElement, Wrapper[].class); 应该工作正常。

答案 1 :(得分:38)

Gson gson = new Gson();
Wrapper[] arr = gson.fromJson(str, Wrapper[].class);

class Wrapper{
    int number;
    String title;       
}

似乎工作正常。但是你的字符串中有一个额外的,逗号。

[
    { 
        "number" : "3",
        "title" : "hello_world"
    },
    { 
        "number" : "2",
        "title" : "hello_world"
    }
]

答案 2 :(得分:14)

public static <T> List<T> toList(String json, Class<T> clazz) {
    if (null == json) {
        return null;
    }
    Gson gson = new Gson();
    return gson.fromJson(json, new TypeToken<T>(){}.getType());
}

示例电话:

List<Specifications> objects = GsonUtils.toList(products, Specifications.class);

答案 3 :(得分:1)

service = discovery.build('drive', 'v3', http=creds.authorize(Http()))
    page_token = None
    while True:
        response = service.files().list(q="mimeType='application/vnd.google-apps.folder' or mimeType='text/plain'",
                                              spaces='drive',
                                              fields='nextPageToken, files(id, name)',
                                              pageToken=page_token).execute()
        print(response)                                              
        for file in response.get('files', []):
            # Process change
            print('Found file: %s (%s)' % (file.get('name'), file.get('id')))

        page_token = response.get('nextPageToken', None)
        if page_token is None:
            break        
相关问题