我想用Jackson2解析Java中的JSON,它具有以下结构:
{
"attachment": {
"_2K26Z-mLJmMSRnssLwD0zQ": {
"ext": "jpg",
"height": 3024,
"md5": "219c226e0070b7367f90e2f1bff1dfc2",
"name": "IMG_1871.jpg",
"ref": "MTUyMTAzNDY5MDUzNElNR18xODcxLmpwZw==",
"rotate": true,
"size": 1514957,
"thumb": "thumb_1024_219c226e0070b7367f90e2f1bff1dfc2",
"thumb_size": 73119,
"type": "image",
"width": 4032
},
"_Q7l14s87UquHcAYoolNCuw": {
"ext": "png",
"height": 186,
"md5": "75023fd60d59907376943bf109858336",
"name": "ns_attach_image_26071520280535225.png",
"ref": "MTUyMDI4MDUzNTIzMG5zX2F0dGFjaF9pbWFnZV8yNjA3MTUyMDI4MDUzNTIyNS5wbmc=",
"rotate": true,
"size": 15182,
"type": "image",
"width": 347
}
},
"title": "Test Title"
}
我的问题是我不知道如何处理附件的密钥,因为我无法使用名称未知的字段定义类。
什么有效
ObjectMapper mapper = new ObjectMapper();
Note note = mapper.readValue(fileio, Note.class);
类注意是
public class Note {
private String title;
private Object attachment;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public Object getAttachment() {
return attachment;
}
public void setAttachment(Object attachment) {
this.attachment = attachment;
}
}
但是我想使用一个带有Name Attachment的类,它使用键" _2K26Z-mLJmMSRnssLwD0zQ"来保存json中的所有字段。
答案 0 :(得分:1)
您可以使用Map
,以便附件的键是地图中的键,地图中的值将是表示附件字段的对象。像这样:
public class Attachment {
private String ext;
private int height;
private String md5;
private String name;
private String ref;
private boolean rotate;
private int size;
private String thumb;
private int thumb_size;
private String type;
private int width;
}
public class Note {
private String title;
private Map<String, Attachment> attachment = new HashMap<>();
}