24

我正在使用 Spring HATEOAS (0.16.0.RELEASE) 构建一个 Spring REST 应用程序,我希望 JSON 链接输出看起来像:

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

虽然它呈现如下:

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

我正在使用 HATEOASResourceResourceAssembler.

为什么我得到这种格式而不是另一种?我怎样才能改变它?

4

2 回答 2

12

为了使用 HAL 作为 RESTful API 的消息格式语言,并启用自动分页,我们需要在应用程序中进行一些配置更改。由于 Spring Data 和 Spring HATEOAS 已经为配置提供了注解,我们只需要添加这些注解即可:

@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 将添加对分页的支持,@EnableHypermediaSupport(type = { HypermediaType.HAL }) 将添加对超媒体的支持。然后我们将默认内容类型设置为 application/hal+json。

引用:使用 Spring HATEOAS 设计和构建 RESTful API由 Yuan Ji

于 2014-09-07T22:11:32.423 回答
1

确保您使用com.fasterxml.jackson依赖项而不是其他依赖项,例如org.codehaus.jackson. 例如,在 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>
于 2015-05-05T08:15:47.350 回答