问题
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://<ip>/api/policies/321"
}
}
while it renders like:
"links":
[{
"rel":"self",
"href":"http://<ip>/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 :
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.5.3</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.5.3</version>
</dependency>
来源:https://stackoverflow.com/questions/25709672/how-to-change-hal-links-format-using-spring-hateoas