返回json意外,将"链接"拼写为"_links"并且结构不同,在Spring hateoas中

Cha*_*had 10 java spring hateoas spring-hateoas spring-boot

正如标题所说,我有一个资源对象Product扩展ResourceSupport.但是,我收到的回复具有属性"_links"而不是"links",并且具有不同的结构.

{
  "productId" : 1,
  "name" : "2",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/products/1"
    }
  }
}
Run Code Online (Sandbox Code Playgroud)

基于HATEOAS参考,预期是:

{
  "productId" : 1,
  "name" : "2",
  "links" : [
    {
      "rel" : "self"
      "href" : "http://localhost:8080/products/1"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

这是有意的吗?有没有办法改变它,或者如果不是结构那么就是"链接"?

我通过以下代码段添加了selfLink:

product.add(linkTo(ProductController.class).slash(product.getProductId()).withSelfRel());
Run Code Online (Sandbox Code Playgroud)

我使用以下构建文件的spring boot:

dependencies {
    compile ("org.springframework.boot:spring-boot-starter-data-rest") {
        exclude module: "spring-boot-starter-tomcat"
    }

    compile "org.springframework.boot:spring-boot-starter-data-jpa"
    compile "org.springframework.boot:spring-boot-starter-jetty"
    compile "org.springframework.boot:spring-boot-starter-actuator"

    runtime "org.hsqldb:hsqldb:2.3.2"

    testCompile "junit:junit"
}
Run Code Online (Sandbox Code Playgroud)

Ton*_*Lxc 5

Spring Boot now(version = 1.3.3.RELEASE)有一个控制输出JSON格式的属性PagedResources.

只需将以下配置添加到您的application.yml文件中:

spring.hateoas.use-hal-as-default-json-media-type: false
Run Code Online (Sandbox Code Playgroud)

如果您需要输出(基于问题):

{
  "productId" : 1,
  "name" : "2",
  "links" : [
    {
      "rel" : "self"
      "href" : "http://localhost:8080/products/1"
    }
  ]
}
Run Code Online (Sandbox Code Playgroud)

编辑:

顺便说一句,您只需要@EnableSpringDataWebSupport以这种方式进行注释.


Pri*_*mre 5

另一种选择是禁用整个超媒体自动配置功能(这是在此处spring-boot+ REST 示例之一中完成的方式):

@EnableAutoConfiguration(exclude = HypermediaAutoConfiguration.class)
Run Code Online (Sandbox Code Playgroud)

据我所知,HypermediaAutoConfiguration除了配置 HAL 之外,实际上并没有做太多事情,因此禁用它应该完全没问题。


use*_*807 5

我注意到至少当您尝试返回扩展 ResourseSupport 的对象与包含扩展 ResourseSupport的对象时,会出现问题。您甚至可以返回扩展 ResourseSupport 的对象列表或数组,并具有相同的效果。请参阅示例:

@RequestMapping(method = GET, value = "/read")
public NfcCommand statusPayOrder() {
    return generateNfcCommand();
}
Run Code Online (Sandbox Code Playgroud)

有回应:

{
    "field": "123",
    "_links": {
        "self": {
            "href": "http://bla_bla_bla_url"
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

当尝试包装为列表时:

@RequestMapping(method = GET, value = "/read")
public List<NfcCommand> statusPayOrder() {
    return Arrays.asList(generateNfcCommand());
}
Run Code Online (Sandbox Code Playgroud)

得到:

[
    {
        "field": 123
        "links": [
            {
                "rel": "self",
                "href": "http://bla_bla_bla_url"
            }
        ]
    }
]
Run Code Online (Sandbox Code Playgroud)

改变答案的结构并不是正确的决定,但我们可以尝试以这种方式进一步思考。


Dav*_*yer 4

如果您有可用的 HAL,Spring Boot 将会为您选择它(“_links”是您通过 HAL 获得的)。您应该能够@EnableHypermediaSupport手动覆盖默认值。