如何将缺少字段的 json 反序列化为 class

How to deserialize json to class with missing fields

我正在学习教程,其中一项任务是使用 gson 反序列化 json。我查看了几篇 SO 帖子,但找不到可以解决我的问题的帖子。我在 JSON 中得到一个数组的字符串表示形式,其字段如下所示:

photoJsonArray

[{"id": "28857102437",
"owner":"9457266@N02",
"secret":"a5f02e005f",
"server":"857",
"farm":1,
"title":"",
"ispublic":1,
"isfriend":0,
"isfamily":0,
"url_s":"https:\/\/farm1.staticflickr.com\/857\/28857102437_a5f02e005f_m.jpg" ...and so on

我想将此列表反序列化为 GalleryItem 个对象的列表,其中仅包含 JSON 中的 idurl_sid 字段]数组。

我尝试了以下方法将 JSON 字符串转换为图库项目对象列表,但所有字段都以 null 值结尾。

 Type photoType = new TypeToken<List<GalleryItem>>(){}.getType();

List<GalleryItem>galleryList = g.fromJson(photoJsonArray.toString(),photoType); 

如果有人能指出正确的方向,我将不胜感激!

经过一些研究,我发现 JSON 字符串中的所有字段都需要在 class 中声明,以便将 JSON 反序列化为 class .如果您只需要使用几个字段,似乎有点矫枉过正,但希望这会有所帮助。