我正在使用Traverson导航“发票和项目”的父子关系。我可以获取资源>并遍历它们以获得单独的发票资源,并使用for ... each循环来开发发票。我想重用Traverson对象来获取发票项目,但是Traverson不想为我合作(还)。
我已经看过问题How to access one element of a REST collection through HATEOAS links?和https://docs.spring.io/spring-hateoas/docs/0.25.0.RELEASE/reference/html/#client.traverson,这几乎可以给我一个答案,但我希望有一个更具体的例子。
String url = baseUrl + invoicesUrl;
Traverson traverson = new Traverson (new URI (url), MediaTypes.HAL_JSON);
ParameterizedTypeReference<Resources<Resource<Invoice>>> invoiceTypeReference =
new ParameterizedTypeReference<Resources<Resource<Invoice>>> () {};
Resources<Resource<Invoice>> invoiceResources =
traverson.follow ("last").toObject (invoiceTypeReference);
ParameterizedTypeReference<Resources<Resource<Item>>> itemTypeReference =
new ParameterizedTypeReference<Resources<Resource<Item>>> () {};
for (Resource<Invoice> invoiceResource : invoiceResources) {
Resources<Resource<Item>> itemResources =
traverson.follow (invoiceResource.getLink ("items").getRel())
.toObject(itemTypeReference); // fails to find the link
}
获取发票资源可以正常工作并返回
{"_embedded":
{"invoiceList":
[{"sourceLastModified":"2019-03-06T22:33:46.000+0000",
"lastModified":"2019-03-06T22:33:46.000+0000",
"validFrom":"2019-03-06T22:33:46.000+0000",
"validTo":"9999-12-31T06:00:00.000+0000",
"etlStageTagId":null,
"etlCrTagId":77,
"etlErrorInd":null,
"uniqueRowId":35,
"openRowInd":"Y",
"id":35,
"seqNum":1,
"fileId":null,
"fileName":null,
"invoiceNumber":"1",
"invoiceDate":"2019-01-18T06:00:00.000+0000",
"invoiceTotal":0.00,
"companyName":"TEST1",
"approvedBy":null,
"approvedOn":null,
"_links":
{"self":{"href":"https://mydomain/myService/invoices/35"},
"invoices":{"href":"https://mydomain/myService/invoices"},
"items": {"href":"https://mydomain/myService/items/invoice/1/company/TEST1"},
"approve":{"href":"https://mydomain/myService/invoices/1/TEST1/approve/appName"
}
}
},
{"sourceLastModified":"2019-03-06T22:33:46.000+0000",
"lastModified":"2019-03-06T22:33:46.000+0000",
"validFrom":"2019-03-06T22:33:46.000+0000",
"validTo":"9999-12-31T06:00:00.000+0000",
"etlStageTagId":null,
"etlCrTagId":77,
"etlErrorInd":null,
"uniqueRowId":36,
"openRowInd":"Y",
"id":36,
"seqNum":1,
"fileId":null,
"fileName":null,
"invoiceNumber":"1",
"invoiceDate":"2019-01-18T06:00:00.000+0000",
"invoiceTotal":-2025.10,
"companyName":"TEST2",
"approvedBy":null,
"approvedOn":null,
"_links":
{"self":{"href":"https://mydomain/myService/invoices/36"},
"invoices":{"href":"https://mydomain/myService/invoices"},
"items":{"href":"https://mydomain/myService/items/invoice/1/company/TEST2"},
"approve":{"href":"https://mydomain/myService/invoices/1/TEST2/approve/appName"
}
}
}]
},
"_links":{"self":{"href":"https://mydomain/myService/invoices"},
"last":{"href":"https://mydomain/myService/invoices/last"
}
}
}
我希望此代码在发票资源中找到链接以获取项目并执行HTTP GET调用。相反,我收到错误消息“ java.lang.IllegalStateException:期望在响应中找到带有rel'items'的链接”。
如何获取Traverson对象以跟随在for ... each循环中检索到的资源中的链接?