3
votes

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.

1
what about returning an HttpEntity<Set<AResource>>? - mugua
I had it both ways, HttpEntity is only adding ok status which if you add ResponseBody annotation does it for you - Luis Ramirez-Monterosa
and then what about returning a List instead of a Set? I doubt it really matters, but I've only seen Lists being returned. Otherwise I'd guess you just need to wrap your array in another ResourceSupport object - mugua
I tried returning a List but same result. I think Spring (or some voodo magic) doesn't work properly with collections in general because I wrap the Set in another Resource and et voilĂ ! The thing adds _links and the header is now hal+json as well., alas, not what I want since I want to return an array not an object with the array. - Luis Ramirez-Monterosa
I think you said it yourself, that returning an array is not really Restful. At least, it doesn't seem to be proper HATEOAS. - mugua

1 Answers

2
votes

"_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.