Luis Ramirez-Monterosa
Luis Ramirez-Monterosa

Reputation: 2242

spring hateoas generates different responses for collection or pojo

I have two classes

import org.springframework.hateoas.ResourceSupport;

public class A{}
public class B{}

public class AResource extends ResourceSupport {
  private final A a;
}
public class BResource extends ResourceSupport {
  private final B b;
}

@Controller
public class Controller {
  @RequestMapping
  @ResponseBody
  public Set<AResource> giveMeColl() {

  }
  @RequestMapping
  @ResponseBody
  public BResource giveMeSingle() {

  }

}

both responses add links object but for resource A is "links" and for resource B is "_link" and also structure changes

//RESPONSE FOR A 
[  
   {  
      "content":{  
         //my fancy object
      },
      "links":[  
        {
        "rel": "self",
        "href":         "http://localhost:8080/myid/22"
        }
      ]
   }
]



{  
    "content":{  
             //my fancy object
    },
    "_links":[  
     {
         "self":         "http://localhost:8080/myid/22/someelse/33"
     }]
 }

both resources are constructed with assemblers and both are adding the link from the ids

AResource aresource = new AResource(a);
resource.add(linkTo(methodOn(Controller.class).giveMeColl()).withSelfRel());

BResource bresource = new BResource(b);
resource.add(linkTo(methodOn(Controller.class).giveMeSingle()).withSelfRel());

Response headers for a is

"content-type": "application/json;charset=UTF-8"

and for b

"content-type": "application/hal+json;charset=UTF-8"

Could it be because returning an array is not really Restful? as Some post suggest

p.s. I have added and removed @EnableHypermediaSupport but doesn't seem to affect the problem.

Upvotes: 3

Views: 1435

Answers (1)

a better oliver
a better oliver

Reputation: 26848

"_links" follows the HAL specification. Spring HATEOAS includes a dedicated serializer for that, but it is only used for classes that extend ResourceSupport.

Returning a simple array is not exactly "unRESTful", but it doesn't meet the REST maturity level 3 (Hypermedia controls). In order to achieve that you can wrap the collection into a Resources instance, which extends ResourceSupport. You should get the same link serialization for both types then.

Upvotes: 2

Related Questions