简体   繁体   中英

How to consume resource with _embedded resources

I'm trying to consume a rest web services with Spring Traverson and basic restTemplate but it's not working...

I consume a rest web service which return :

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

I want to have resource classes on Java side who looks like these :

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;
}

How can I use RestTemplate or Traverson with Resource, Resources or ResourceSupport classes to match these java objects ?

Your structure doesn't look quite right. For example, _embedded is mapped onto Spring HATEOAS Resources , which is designed to handle a list of resources. But your record shows _embedded not containing a list but simply a nested structure.

You also have top level attributes in your structure, which don't map onto the Resources type.

If I was to model Author and Book (a bit simplified) and export it with Spring Data REST (with author inlined to books), it would look like this:

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

If I dig into a single book, the record looks like this:

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

Reading the HAL spec , any _embedded element maps onto arrays.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM