我有一个Spring Rest Controller,它接受请求作为Xml。这是示例请求格式。
<Message>
<Header id="101" desc="Header content description">
<title text="The quick brown fox" />
</Header>
<Content />
<Footer name="test">Footer content sample.</Footer>
</Message>
这是我的控制器:
@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!";
}
}
对于Message类,我有以下类:
@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.
}
}
标题类:
@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...
}
内容分类:
@XmlRootElement(name = "Content")
@XmlAccessorType(XmlAccessType.FIELD)
public class Content {
}
和对于Footer类:
@XmlRootElement(name = "Footer")
@XmlAccessorType(XmlAccessType.FIELD)
public class Footer {
@XmlValue
private String value;
@XmlAttribute(name = "name")
private String name;
//Getter and setters here...
}
所以我在输出中看到了三个问题:
标头中的描述属性值始终为空。基本上,我想在类中使用不同的字段名称,但要从XML读取属性(“ desc”)。不过,属性“ id”很好,我可以从中检索值。
它不能生成空的Content XML,例如。如果我将nillable = true放置,它将生成具有额外属性的Content,例如xmnls =“ ...” />。不确定如何删除这些额外的属性,以便仅生成空的内容元素。
可以读取页脚属性“名称”值,但不能读取表示“页脚内容样本”的文本。
有什么想法吗?
答案 0 :(得分:0)
此问题已解决。糟糕的是我从gradle文件中导入了以下内容。
compile('com.fasterxml.jackson.dataformat:jackson-dataformat-xml')
因此,通过从build.gradle中删除它,一切都会按预期进行!