I have a requirement to pass a custom object using RESTTemplate to my REST service.
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........");
I'm not able to add my custom object to MultiValueMap. Request generation is getting failed.
Can someone helps me to find a way for this? I can simply pass a string object without problem.User defined objects makes the problem.
Appreciate any help !!!
Using postForEntity()Find the postForEntity method declaration from Spring doc. url: The URL to post the request. request: The object to be posted. responseType: The type of response body.
You can use the annotation @JsonRootName to specify the root element in your response. So try this: @JsonIgnoreProperties(ignoreUnknown = true) @JsonRootName(value ="result") public class User { public User(){ } private boolean admin; .... }
You can do it fairly simply with Jackson.
Here is what I wrote for a Post of a simple 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);
The link above should tell you how to set it up if needed. Its a pretty good tutorial.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With