Returned json unexpected, has "links" spelled as "_links" and structure different, in Spring hateoas

Chad picture Chad · Aug 21, 2014 · Viewed 10.8k times · Source

As the title says, I have a resource object Product extending ResourceSupport. However, the responses I receive have the property "_links" instead of "links" and have a different structure.

{
  "productId" : 1,
  "name" : "2",
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/products/1"
    }
  }
}

Based on the HATEOAS Reference, the expected is:

{
  "productId" : 1,
  "name" : "2",
  "links" : [
    {
      "rel" : "self"
      "href" : "http://localhost:8080/products/1"
    }
  ]
}

Was this intended? Is there a way to change it, or at leas the "link" if not the structure?

I added the selfLink through the following snippet:

product.add(linkTo(ProductController.class).slash(product.getProductId()).withSelfRel());

I am using spring boot with the following build file:

dependencies {
    compile ("org.springframework.boot:spring-boot-starter-data-rest") {
        exclude module: "spring-boot-starter-tomcat"
    }

    compile "org.springframework.boot:spring-boot-starter-data-jpa"
    compile "org.springframework.boot:spring-boot-starter-jetty"
    compile "org.springframework.boot:spring-boot-starter-actuator"

    runtime "org.hsqldb:hsqldb:2.3.2"

    testCompile "junit:junit"
}

Answer

TonyLxc picture TonyLxc · Jun 15, 2016

Spring Boot now (version=1.3.3.RELEASE) has a property that controls the output JSON format of the PagedResources.

Just add the following config to your application.yml file:

spring.hateoas.use-hal-as-default-json-media-type: false

if you need the output to be like (based on question):

{
  "productId" : 1,
  "name" : "2",
  "links" : [
    {
      "rel" : "self"
      "href" : "http://localhost:8080/products/1"
    }
  ]
}

Edited:

By the way, you only need @EnableSpringDataWebSupport annotation in this way.