3

我的 URI 是 http://localhost:8080/context/my-objects/search/findByCode?code=foo

JSON响应:

{
  "_embedded" : {
    "my-objects" : [ {
      "code" : "foo",
      "description" : "foo description",
      "_links" : {
        "self" : {
          "href" : "http://localhost:8080/context/my-objects/34"
        }
      }
    } ]
  }
}

如何获得带有 Traverson 或 RestTemplate 的 java MyObject?

import org.springframework.hateoas.ResourceSupport;

public class MyObject extends ResourceSupport{

    private String code;

    private String description;

    public String getDescription() {
        return description;
    }

    public void setDescription(final String description) {
        this.description = description;
    }

    public String getCode() {
        return code;
    }

    public void setCode(final String code) {
        this.code = code;
    }

}

这是我的模板。我也尝试过使用默认的。

{
ObjectMapper mapper = new ObjectMapper();
mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
mapper.registerModule(new Jackson2HalModule());

MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
converter.setSupportedMediaTypes(MediaType.parseMediaTypes("application/hal+json"));
converter.setObjectMapper(mapper);

RestTemplate template = new RestTemplate(Collections.<HttpMessageConverter<?>> singletonList(converter));

}

提前谢谢。

4

1 回答 1

5

我找到了解决方案。首先,创建一个资源类:

import org.springframework.hateoas.Resources;

public class MyObjects extends Resources<MyObject> { }

然后就很简单了:

MyObjects myObjects = template.getForObject("http://localhost:8080/context/my-objects/search/findByCode?code=foo", MyObjects.class);

注意:模板应支持 hal+json 媒体类型。

或与特拉弗森:

import org.springframework.hateoas.MediaTypes;
import org.springframework.hateoas.client.Traverson;

Traverson traverson;
try{
    traverson = new Traverson(new URI("http://localhost:8080/context"), MediaTypes.HAL_JSON);
    Map<String, Object> parameters = new HashMap<String, Object>();
    parameters.put("code", "foo");

    MyObjects myObjects = traverson.follow("my-objects", "search", "findByCode").withTemplateParameters(
                parameters).toObject(MyObjects.class);
} catch (URISyntaxException e) {}

如果您不想使用 ResourceSupport 类扩展 POJO MyObject,则应使用 Resource 键入 Resources 类:

import org.springframework.hateoas.Resource;
import org.springframework.hateoas.Resources;

public class MyObjects extends Resources<Resource<MyObject>> { }

(如果您不需要链接,则类型参数可能又是 MyObject)。

于 2015-02-09T09:54:07.263 回答