如何使用Spring的REST模板传递自定义对象 [英] How to Pass custom objects using Spring's REST Template

查看:0
本文介绍了如何使用Spring的REST模板传递自定义对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求使用RESTTemplate将自定义对象传递给我的REST服务。

RestTemplate restTemplate = new RestTemplate();
MultiValueMap<String, Object> requestMap = new LinkedMultiValueMap<String, Object>();
...

requestMap.add("file1", new FileSystemResource(..);
requestMap.add("Content-Type","text/html");
requestMap.add("accept", "text/html");
requestMap.add("myobject",new CustomObject()); // This is not working
System.out.println("Before Posting Request........");
restTemplate.postForLocation(url, requestMap);//Posting the data.
System.out.println("Request has been executed........");

无法将我的自定义对象添加到MultiValueMap。请求生成失败。

有人能帮我找到解决这个问题的方法吗?我可以简单地传递一个字符串对象,但问题是由用户定义的对象造成的。

感谢您的帮助!

推荐答案

You can do it fairly simply with Jackson

这是我为一篇简单POJO的帖子写的。

@XmlRootElement(name="newobject")
@JsonSerialize(include=JsonSerialize.Inclusion.NON_NULL)
public class NewObject{
    private String stuff;

    public String getStuff(){
        return this.stuff;
    }

    public void setStuff(String stuff){
        this.stuff = stuff;
    }
}

....
//make the object
NewObject obj = new NewObject();
obj.setStuff("stuff");

//set your headers
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_JSON);

//set your entity to send
HttpEntity entity = new HttpEntity(obj,headers);

// send it!
ResponseEntity<String> out = restTemplate.exchange("url", HttpMethod.POST, entity
    , String.class);
如果需要,上面的链接应该会告诉您如何设置它。这是一个很好的教程。

这篇关于如何使用Spring的REST模板传递自定义对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆