How to change HAL links format using Spring HATEOAS

匿名 (未验证) 提交于 2019-12-03 02:06:01

问题:

I'm building a Spring REST application using Spring HATEOAS (0.16.0.RELEASE) and I'd like the JSON links output to look like:

_links: {    self: {      href: "https:///api/policies/321"    } }

while it renders like:

   "links":       [{        "rel":"self",        "href":"http:///api/policies/321"       }]

I'm using HATEOAS Resource and ResourceAssembler.

Why do I get this format instead of the other? How can I change it?

回答1:

In order to use HAL as the message format language for our RESTful API, and enable automatic pagination, we need some configuration changes in our applicaiton. Since Spring Data and Spring HATEOAS already provides annotations for configuration, all we need is to add those annotations:

@Configuration @EnableWebMvc @EnableSpringDataWebSupport @EnableHypermediaSupport(type = { HypermediaType.HAL }) @ComponentScan(basePackages = {         "com.jiwhiz.rest" }) public class WebConfig extends WebMvcConfigurerAdapter {     @Override     public void configureContentNegotiation(ContentNegotiationConfigurer c) {         c.defaultContentType(MediaTypes.HAL_JSON);     } }

@EnableSpringDataWebSupport will add support for pagination and @EnableHypermediaSupport(type = { HypermediaType.HAL }) will add hypermedia support. Then we set default content type to application/hal+json.

cite: Design and Build RESTful API with Spring HATEOAS by Yuan Ji



回答2:

Make sure that your using com.fasterxml.jackson dependency instead of others like org.codehaus.jackson. For example, in a Maven pom.xml :

                     com.fasterxml.jackson.core             jackson-core             2.5.3                               com.fasterxml.jackson.core             jackson-databind             2.5.3                               com.fasterxml.jackson.core             jackson-annotations             2.5.3         


回答3:

Make sure that you set the Accept request header as follows:

Accept: application/hal+json


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!