gpt4 book ai didi

java - 返回 json 意外,在 Spring 中将 "links"拼写为 "_links"并且结构不同

转载 作者:IT老高 更新时间:2023-10-28 13:49:02 25 4
gpt4 key购买 nike

正如标题所说,我有一个资源对象 Product 扩展 ResourceSupport。但是,我收到的响应具有属性“_links”而不是“链接”,并且具有不同的结构。

{
"productId" : 1,
"name" : "2",
"_links" : {
"self" : {
"href" : "http://localhost:8080/products/1"
}
}
}

基于 HATEOAS Reference ,预期为:

{
"productId" : 1,
"name" : "2",
"links" : [
{
"rel" : "self"
"href" : "http://localhost:8080/products/1"
}
]
}

这是故意的吗?有没有办法改变它,或者如果不是结构,至少是“链接”?

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

product.add(linkTo(ProductController.class).slash(product.getProductId()).withSelfRel());

我正在使用带有以下构建文件的 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"
}

最佳答案

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

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

spring.hateoas.use-hal-as-default-json-media-type: false

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

{
"productId" : 1,
"name" : "2",
"links" : [
{
"rel" : "self"
"href" : "http://localhost:8080/products/1"
}
]
}

已编辑:

对了,这种方式只需要@EnableSpringDataWebSupport注解即可。

关于java - 返回 json 意外,在 Spring 中将 "links"拼写为 "_links"并且结构不同,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25431087/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com