如何从Spring ResponseEntity返回不带包装的JSON?

控制器返回ResponseEntity

@GetMapping("/users/{id}")
public ResponseEntity<UserResource> getUserById{}

用户资源是从RestResource扩展的

public class UserResource extends ResourceSupport {}

当我调用其余的API时,我会得到

 {
      "user": {
        "id": 49,"firstName": "Admin"
      },"links": [
        {...}]
    }

如何在没有顶层包装的情况下获得它?这样吗?

{
  "id": 49,"firstName": "Admin"
}

这很有趣,因为当我使用Spring Data Rest时,返回的数据实际上是后一种,但是SDR也使用Spring-HATEOAS。

a8496558 回答:如何从Spring ResponseEntity返回不带包装的JSON?

您不需要创建ResponseEntity。只需返回对象:

@ResponseBody
@GetMapping("/users/{id}")
public UserResource getUserById() {
   // your method
   return new UserResource();
}

如果您想使用HATEOAS,恐怕没有办法将有效负载放在根中(不包装)。但是您也可以不使用ResponseEntity返回对象:https://www.baeldung.com/spring-hateoas-tutorial

,

结果……关键是不要返回扩展ResourceSupport的自己的Resource对象。

相反,只需返回org.springframework.hateoas.Resource,由于某种原因,该资源将被序列化为扁平结构,而不是被包装。

,

您也可以使用自己的Resource对象来扩展ResourceSupport。

诀窍是您需要在content属性上使用JACKSON批注:

@JsonUnwrapped
public T getContent() {
    return content;
}
本文链接:https://www.f2er.com/3163569.html

大家都在问