【问题标题】:How to consume resource with _embedded resources如何使用 _embedded 资源消耗资源
【发布时间】:2015-10-30 02:20:03
【问题描述】:

我正在尝试使用 Spring Traverson 和基本的 restTemplate 使用休息 Web 服务,但它不起作用...

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

获取 /books/1 内容类型:应用程序/hal+json { “标题”:“悲惨世界”, “国际标准书号”:“9780685113974”, “_嵌入”:{ “作者”: { "firstName": "维克多", "姓氏": "雨果" , “出生”:“18020226”, “死”:“18850522” }, “元”:{ “类型”:“经典”, “国家”:“法国” } } }

我想在 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;
}

如何使用带有 Resource、Resources 或 ResourceSupport 类的 RestTemplate 或 Traverson 来匹配这些 java 对象?

【问题讨论】:

    标签: resttemplate hateoas spring-hateoas consuming


    【解决方案1】:

    您的结构看起来不太正确。例如,_embedded 映射到 Spring HATEOAS Resources,它旨在处理资源列表。但是您的记录显示 _embedded 不包含列表,而只是一个嵌套结构。

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

    如果我要对 Author 和 Book 建模(稍微简化)并使用 Spring Data REST 将其导出(作者内联到书籍),它看起来像这样:

    $ 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"
        }
      }
    }
    

    如果我深入研究一本书,记录是这样的:

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

    读取HAL spec,任何_embedded 元素都会映射到数组中。

    【讨论】:

      猜你喜欢
      • 2018-03-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-12
      • 1970-01-01
      • 1970-01-01
      • 2017-12-03
      • 1970-01-01
      相关资源
      最近更新 更多