Spring hateoas如何设置关系并且还有单链接数组

时间:2015-11-30 13:52:43

标签: java spring-boot spring-hateoas

有人可以让我知道如何使用hateoas得到以下回应

{
    "ticketID" : 345,
    "links": [ {
        "rel": "self",
        "href": "rest/INL_TM/rest/v1/ticket/345"
    } ]
}

但我得到了回应

{
    "ticketID" : 345,
    "links":  {
        "rel": "self",
        "href": "rest/INL_TM/rest/v1/ticket/345"
    }
}

另外,如何将rel设置为自定义值?我想要像rel =" getTicket"

这样的东西

Greeting.java

public class Greeting extends ResourceSupport {

    private final String content;

    @JsonCreator
    public Greeting(@JsonProperty("content") String content) {
        this.content = content;
    }

    public String getContent() {
        return content;
    }
}

GreetingController.java

@Controller
public class GreetingController {

    private static final String TEMPLATE = "Hello, %s!";

    @RequestMapping("/greeting")
    @ResponseBody
    public HttpEntity<Greeting> greeting(
            @RequestParam(value = "name", required = false, defaultValue = "World") String name) {

        Greeting greeting = new Greeting(String.format(TEMPLATE, name));
        greeting.add(linkTo(methodOn(GreetingController.class).greeting(name)).withSelfRel());

        return new ResponseEntity<Greeting>(greeting, HttpStatus.OK);
    }
}

提前致谢

1 个答案:

答案 0 :(得分:0)

在模型类中扩展ResourceSupport。 返回资源而不是ResponseEntity

GreetingController.java

@Controller
public class GreetingController {       

@RequestMapping("/greeting")
@ResponseBody
public Resource<Greeting> greeting(
@RequestParam(value = "name", required = false, defaultValue = "World") String name) {

Resource<Greeting> resourceResponse = new Resource<Greeting>("Some String");
resourceResponse.add(linkTo(methodOn(GreetingController.class).greeting("Some String")).withSelfRel());
return resourceResponse;
   }
}

Maven依赖

<dependency>
   <groupId>org.springframework.hateoas</groupId>
   <artifactId>spring-hateoas</artifactId>
   <version>0.16.0.RELEASE</version>
</dependency>