Reputation: 105
I have a Spring Rest Controller, that accepts request as Xml. This is the sample request format coming in.
<Message>
<Header id="101" desc="Header content description">
<title text="The quick brown fox" />
</Header>
<Content />
<Footer name="test">Footer content sample.</Footer>
</Message>
this is my controller:
@RestController
@RequestMapping("myservice")
public class MessageController {
@PostMapping(consumes = MediaType.APPLICATION_XML_VALUE)
public String handler(@RequestBody Message message) {
System.out.println(message);
System.out.println("\n\n\n");
try {
JAXBContext jaxbContext = JAXBContext.newInstance(Message.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(message, System.out);
} catch(JAXBException ex) {
System.out.println(ex.toString());
}
return "Done!";
}
}
and I have the following classes, for the Message class:
@XmlAccessorType(XmlAccessType.FIELD)
@XmlRootElement(name = "Message")
public class Message {
@XmlElement(name = "Header", required = true)
private Header header;
@XmlElement(name = "Content", required = true)
private Content content;
@XmlElement(name = "Footer", required = true)
private Footer footer;
// Getters and setters here...
@Override
public String toString() {
// In here, I outputted the values of the header and footer.
}
}
Header class:
@XmlRootElement(name = "Header")
@XmlAccessorType(XmlAccessType.FIELD)
public class Header {
@XmlAttribute(name = "id", required = true)
private String id;
@XmlAttribute(name = "desc", required = true)
private String description;
// Getters and setters here...
}
Content class:
@XmlRootElement(name = "Content")
@XmlAccessorType(XmlAccessType.FIELD)
public class Content {
}
and for the Footer class:
@XmlRootElement(name = "Footer")
@XmlAccessorType(XmlAccessType.FIELD)
public class Footer {
@XmlValue
private String value;
@XmlAttribute(name = "name")
private String name;
//Getter and setters here...
}
So there are three issues that I see here from the output:
The description attribute value from the Header is always null. Basically I wanted to have a different field name in the class but reading an attribute ("desc") from the XML. The attribute "id" is fine though, I can retrieve the value from it.
It can't generate an empty Content XML e.g. . If I put nillable=true, it will generate Content with extra attributes e.g. xmnls="..." />. Not sure how to remove those extra attributes so that it generates only empty content element.
Footer attribute "name" value can be read but not the text that says "Footer content sample".
Any thoughts?
Upvotes: 0
Views: 1022
Reputation: 105
This has been resolved. My bad that I imported the following from my gradle file.
compile('com.fasterxml.jackson.dataformat:jackson-dataformat-xml')
So by removing this from build.gradle, everything works as expected!
Upvotes: 1