如何使用_embedded资源来使用资源

时间:2015-08-06 19:23:14

标签: resttemplate hateoas spring-hateoas consuming

我尝试使用Spring Traverson和基本的restTemplate来使用其他Web服务,但它没有工作......

我使用了一个返回的休息网络服务:

GET /books/1
ContentType: application/hal+json
{
    "title": "Les Misérables" ,
    "ISBN": "9780685113974",
    "_embedded": {
        "author": {
            "firstName": "Victor" ,
            "lastName": "Hugo" ,
            "born": "18020226",
            "died": "18850522"
        },
        "meta": {
            "type": "classic" ,
            "country": "FR"
        }
    }
}

我希望Java端的资源类看起来像这样:

class Book {
    String title;
    String isbn;
    Author author;
    Meta meta;
}

class Author {
    String firstName;
    String lastName;
    Date born;
    Date died;
}

class Meta {
    String type;
    String country;
}

如何使用RestTemplate或Traverson与Resource,Resources或ResourceSupport类来匹配这些java对象?

1 个答案:

答案 0 :(得分:1)

你的结构看起来不太对劲。例如,_embedded映射到Spring HATEOAS 资源,它用于处理资源列表。但是你的记录显示_embedded不包含列表,只是一个嵌套结构。

您的结构中也有顶级属性,不会映射到资源类型。

如果我要模拟作者和书籍(稍微简化)并使用Spring Data REST(作者内联到书籍)导出它,它将如下所示:

require

如果我挖掘一本书,记录看起来像这样:

$ curl localhost:8080/books/
{
  "_embedded" : {
    "books" : [ {
      "title" : "Learning Spring Boot",
      "author" : {
        "firstName" : "Greg",
        "lastName" : "Turnquist"
      },
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/books/1"
        },
        "book" : {
          "href" : "http://localhost:8080/books/1"
        }
      }
    } ]
  },
  "_links" : {
    "self" : {
      "href" : "http://localhost:8080/books/"
    },
    "profile" : {
      "href" : "http://localhost:8080/profile/books"
    }
  }
}

阅读HAL spec,任何_embedded元素映射到数组。