通过traverson到java对象查找Spring引导数据

时间:2015-02-06 18:05:29

标签: rest spring-boot resttemplate spring-hateoas findby

我的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));

}
提前谢谢。

1 个答案:

答案 0 :(得分:5)

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

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媒体类型。

或者使用Traverson:

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

(如果您不需要链接,则type参数可能再次为MyObject)。