Convert Xml request to Object Spring Boot
Your Post request will have a "content-type" which needs to match up to the "consumes" parameter for your request mapping.
For XML there are two types "application/xml" and "text/xml" it is good practice to accept both, (MediaType.APPLICATION_XML_VALUE
& MediaType.TEXT_XML_VALUE
).
Additionally you have:
produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE}
this is your return type, you only need to define this once you are actually returning something, seeing as are only setting a status code then this should be removed.
Related videos on Youtube
Akhil
Updated on June 04, 2022Comments
-
Akhil almost 2 years
Created a spring boot rest service which accepts XML as a request and converts it into object and then inserts it into database. I used Jackson dataformat dependency for directly converting the xml request to object but getting an error .
The controller class is as follows
@RequestMapping(value = "/getRequestData",method=RequestMethod.POST, produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},consumes={MediaType.APPLICATION_XML_VALUE}) public ResponseEntity<?> putDataIntoDatabase(@RequestBody FirstRequestorBean bean) { logger.info(bean.getId()); return new ResponseEntity<String>(HttpStatus.OK); }
and bean class
public class FirstRequestorBean { private String name; private String id; public String getName() { return name; } public void setName(String name) { this.name = name; } public String getId() { return id; } public void setId(String id) { this.id = id; } }
the xml passed here is
<?xml version="1.0" encoding="UTF-8"?> <FirstRequestorBean> <name>Akhil</name> <id>1</id> </FirstRequestorBean>
getting a Unsupported Media Type exception.
can someone point out how to resolve the issue
-
CrazySabbath almost 7 yearsTry removing your XML file header
<?xml version="1.0" encoding="UTF-8"?>
and try addingMediaType.TEXT_XML
. -
Akhil almost 7 yearsproduces = {MediaType.TEXT_XML_VALUE},consumes={MediaType.TEXT_XML_VALUE}) tried adding this @CrazySabbath .still the same error
-
CrazySabbath almost 7 yearsEither you misspelled your comment, or you didn't understand me. Have you tried adding
TEXT_XML
(notice, notTEXT_XML_VALUE
) and removing xml header? -
Akhil almost 7 years@CrazySabbath yes. I tried removing xml header and using the Mediatype.TEXT_XML .still fetched me the same error
-
-
Akhil almost 7 yearsI have tried both the specific steps but still getting an error
-
MartinByers almost 7 yearsWhat is the content type for your request?
-
Akhil almost 7 yearsHi MartinByers, I was able to resolve the issue ,supposedly was using a tool Jmeter for which I had not set the appropriate Accept Headers , after which it worked.More of a tool settings issue then it was of code.Thank you for the support
-
PAA over 4 years@MartinByers - Could you please guide me here: stackoverflow.com/questions/59485326/…?