use*_*825 3 rest findby resttemplate spring-hateoas spring-boot
我的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"
}
}
} ]
}
}
Run Code Online (Sandbox Code Playgroud)
如何使用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;
}
}
Run Code Online (Sandbox Code Playgroud)
这是我的模板.我也试过一个默认的.
{
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));
}
Run Code Online (Sandbox Code Playgroud)
Thx提前.
我找到了解决方案.首先,创建一个Resources类:
import org.springframework.hateoas.Resources;
public class MyObjects extends Resources<MyObject> { }
Run Code Online (Sandbox Code Playgroud)
然后它很简单:
MyObjects myObjects = template.getForObject("http://localhost:8080/context/my-objects/search/findByCode?code=foo", MyObjects.class);
Run Code Online (Sandbox Code Playgroud)
注意:模板应支持hal + json Media Type.
或者使用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) {}
Run Code Online (Sandbox Code Playgroud)
如果您不想使用ResourceSupport类扩展POJO MyObject,则应使用Resource键入您的Resources类:
import org.springframework.hateoas.Resource;
import org.springframework.hateoas.Resources;
public class MyObjects extends Resources<Resource<MyObject>> { }
Run Code Online (Sandbox Code Playgroud)
(如果您不需要链接,则type参数可能再次为MyObject).
| 归档时间: |
|
| 查看次数: |
2938 次 |
| 最近记录: |