getUserById{} User resource is extended from RestReso" /> getUserById{} User resource is extended from RestReso" /> getUserById{} User resource is extended from RestReso"/>

How to return JSON without wrapper from Spring ResponseEntity?

1.3k Views Asked by At

Controller returns ResponseEntity

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

User resource is extended from RestResource

public class UserResource extends ResourceSupport {}

When I call the rest API, I get

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

How do I get it without the top level wrapped? like this?

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

It's interesting because when I use Spring Data Rest, the data returned is actually the latter kind but SDR also uses Spring-HATEOAS.

3

There are 3 best solutions below

2
pedrohreis On

You do not need to create a ResponseEntity. Simply return the object:

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

If you wanna use HATEOAS, I afraid there is no way to have your payload in the root (without wrapping). But you also can return the object without the ResponseEntity: https://www.baeldung.com/spring-hateoas-tutorial

0
erotsppa On

Turns out...the key is to not return your own Resource object that extends ResourceSupport.

Instead just return org.springframework.hateoas.Resource which for some reason will be serialized as flat structure, not wrapped.

0
Selindek On

You can use your own Resource object that extends ResourceSupport too.

The trick is that you need to use a JACKSON annotation on the content property:

@JsonUnwrapped
public T getContent() {
    return content;
}