1

我正在尝试使用 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 对象?

4

1 回答 1

1

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

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

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

$ 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 规范,任何 _embedded 元素都映射到数组上。

于 2015-09-24T01:59:19.910 回答