问题描述
我收到来自 Alfresco 的 REST 响应,如下所示:
{
"list": {
"pagination": {
"count": 2,"hasMoreItems": false,"totalItems": 2,"skipCount": 0,"maxItems": 100
},"entries": [
{
"entry": {
"createdAt": "2021-07-28T16:01:52.607+0000","isFolder": false,"isFile": true,"createdByUser": {
"id": "admin","displayName": "Administrator"
},"modifiedAt": "2021-07-28T16:01:53.616+0000","modifiedByUser": {
"id": "admin","name": "site1-export.zip","id": "9591936a-82ac-4acc-a75c-29dbaffcae77","nodeType": "cm:content","content": {
"mimeType": "application/zip","mimeTypeName": "ZIP","sizeInBytes": 22089,"encoding": "UTF-8"
},"parentId": "9b211145-5359-4d69-9cbc-7247ba2def21"
}
},{
"entry": {
"createdAt": "2021-07-27T15:58:20.655+0000","modifiedAt": "2021-07-27T15:58:20.655+0000","name": "zzTestPdf.pdf","id": "58833967-6c26-448a-8be1-9387312028e1","nodeType": "customprefixemp:employee_custom_type","content": {
"mimeType": "application/pdf","mimeTypeName": "Adobe PDF Document","sizeInBytes": 8037,"parentId": "9b211145-5359-4d69-9cbc-7247ba2def21"
}
}
]
}
}
这是我如何使用 jayway
ResponseEntity<String> response = restTemplate.exchange(theUrl,HttpMethod.GET,entity,String.class);
JSONObject obj_JSONObject = new JSONObject(response.getBody()).getJSONObject("list");
Configuration cf = Configuration.builder().options(Option.SUPPRESS_EXCEPTIONS).build();
DocumentContext ctx = JsonPath.using(cf).parse(obj_JSONObject.toString());
使用 jayway 我得到 ids 并像下面这样迭代:
List<String> objListItemsId = ctx.read("$.entries[*].entry.id");
for (String fileId : objListItemsId) {
logger.info("FileID - " + fileId);
//logger.info("What should I do here??: " + fileId + "_" + fileName + "_" + nodeType + "_" + mimeType + "_" + mimeTypeName);
}
问题 1:
我也需要其他细节。那么,如何获取其他参数的值,例如 - name
、nodeType
、mimeType
和 mimeTypeName
?我想在一行中为每个 entry
打印这些值。我愿意接受任何解决方案。
更新: 现在,我正在使用这种(肮脏的)方式:
List<String> objListItemsId = ctx.read("$.entries[*].entry.id");
List<String> objListItemsName = ctx.read("$.entries[*].entry.name");
List<String> objListItemsNodeType = ctx.read("$.entries[*].entry.nodeType");
List<String> objListItemsContent = ctx.read("$.entries[*].entry.content.mimeType");
for (int listlen = 0; listlen < objListItemsId.size(); listlen ++) {
System.out.println(objListItemsId.get(listlen) + "," + objListItemsName.get(listlen)+ "," +objListItemsNodeType.get(listlen) + "," + objListItemsContent.get(listlen));
}
问题 2:是否有更好的方法来实现上述目标?
解决方法
虽然我不知道 ctx
的类型,但肯定有更好的方法,但我假设它是某种 serde 库。大多数 serde 库允许您反序列化为给定的对象。
改进您的解决方案:
- 创建一个名为
Entry
的类。它看起来像:
public class Entry {
String createdAt;
String name;
String id;
// add other members from API
}
- 然后你可以这样做:
//this will depend on serde library your are using. Read its docs.
List<Entry> objListItemsId = ctx.read("$.entries[*].entry",Entry.class);
它将在 Entry
实例中反序列化您想要的所有内容。
更新
为了进一步简化解析,您可以去掉 entry
数组中的 entries
。所以,而不是有
"entries": [
{
"entry": {
你可以有
"entries": [
{
// entry 1 details
},{
// entry 2 details
}
...