在 2.0.2.RELEASE 版本中将 Spring Data REST 与 JPA 结合使用。
如何在 JSON 中禁用超文本应用程序语言 (HAL)? http://stateless.co/hal_specification.html
我已经尝试了很多东西,但都无济于事。例如,我将 Accept 和 Content-type header 设置为“application/json”而不是“application/hal+json”,但我仍然收到带有超链接的 JSON 内容。
例如,我想得到类似的东西:
{
"name" : "Foo",
"street" : "street Bar",
"streetNumber" : 2,
"streetLetter" : "b",
"postCode" : "D-1253",
"town" : "Munchen",
"country" : "Germany",
"phone" : "+34 4410122000",
"vat" : "000000001",
"employees" : 225,
"sector" : {
"description" : "Marketing",
"average profit": 545656665,
"average employees": 75,
"average profit per employee": 4556
}
}
代替:
{
"name" : "Foo",
"street" : "street Bar",
"streetNumber" : 2,
"streetLetter" : "b",
"postCode" : "D-1253",
"town" : "Munchen",
"country" : "Germany",
"phone" : "+34 4410122000",
"vat" : "000000001",
"employees" : 225,
"_links" : {
"self" : {
"href" : "http://localhost:8080/app/companies/1"
},
"sector" : {
"href" : "http://localhost:8080/app/companies/1/sector"
}
}
}
感谢您的帮助。
最佳答案
Spring Data REST 的默认设置使用 HAL 作为默认的超媒体表示格式,因此服务器将为给定的 Accept
header 返回以下内容:
application/hal+json
-> HALapplication/hal+json
-> application/hal+json
-> HALapplication/json
-> application/json
-> HAL(这是默认配置)application/x-spring-data-verbose+json
-> application/x-spring-data-verbose+json
-> Spring Data 特定格式(使用links
用于链接容器,content
作为集合项的包装器。如果您将 RepositoryRestConfiguration.setDefaultMediaType(…)
配置为非 HAL 格式,则服务器将返回 Spring Data 特定的 JSON 格式,除非您明确要求 application/hal+json
。诚然,配置选项可能有点误导,所以我提交了 DATAREST-294改善这一点。该问题已在 2014 年 2.1 RC1 (Dijkstra) 中得到解决。
请注意,我们实际上需要一种超媒体格式,以便能够表达托管资源之间的关系并实现服务器的可发现性。所以你不可能完全摆脱它。这主要是因为如果您暴露具有双向关系的实体或构成一个巨大的对象图,您很容易使服务器崩溃。
如果您不想将扇区链接到它们并始终将它们内联,则一种选择是首先简单地将 SectorRepository
排除在导出为 REST 资源之外。您可以通过使用 @RepositoryRestResource(exported = false)
注释存储库接口(interface)来实现此目的。
要获得您在下例中发布的表示返回,请查看 projections Spring Data REST 2.1 M1 中引入的功能。它基本上允许您通过一个简单的界面在资源上制作与默认 View 不同的可选 View 。
你基本上会定义一个接口(interface):
@Projection(name = "foo", types = YourDomainClass.class)
interface Inlined {
// list all other properties
Sector getSector();
}
如果您将此接口(interface)放入域类的(子)包中或通过 RepositoryRestConfiguration.projectionConfiguration()
手动注册它,则暴露 YourDomainClass
的资源将接受请求参数 projection
以便在此示例中传入 foo
将呈现您想要的内联表示。
This commit有更多关于一般特性的信息,this commit定义了一个示例投影。
https://stackoverflow.com/questions/23264044/