spring-boot - JAXB @XmlValue Not Working
问题描述
SampleMessage class:
@XmlRootElement(name = "SampleMessage")
@XmlAccessorType(XmlAccessType.FIELD)
public class SampleMessage {
@XmlAttribute
private String type;
@XmlElement(name = "Content", required = true)
private Content content;
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
public Content getContent() {
return content;
}
public void setContent(Content content) {
this.content = content;
}
@XmlAccessorType(XmlAccessType.FIELD)
private static class Content {
@XmlValue
private String value;
@XmlAttribute(name = "name")
private String name;
public String getValue() {
return value;
}
public void setValue(String value) {
this.value = value;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
}
The Spring Boot - Rest Controller I have the follow method which basically just output the same XML form with what we passed, well supposed to be. This is just to check if it is parsing the XML properly.
@PostMapping(consumes = {MediaType.TEXT_XML_VALUE, MediaType.APPLICATION_XML_VALUE})
public String handler(@RequestBody SampleMessage message) {
StringWriter writer = new StringWriter();
try {
JAXBContext jaxbContext = JAXBContext.newInstance(SampleMessage.class);
Marshaller marshaller = jaxbContext.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
marshaller.marshal(message, writer);
} catch (JAXBException ex) {
System.out.println(ex.toString());
}
return writer.toString();
}
XML Sample 1: This is the initial XML sample I have:
<?xml version="1.0" encoding="UTF-8"?>
<SampleMessage type="TestType">
<Content name="TestContent">This is a sample content.</Content>
</SampleMessage>
Output (XML Sample 1): The output I get from the marshaller is this:
<?xml version="1.0" encoding="UTF-8"?>
<SampleMessage type="TestType">
<Content name="TestContent"/>
</SampleMessage>
Notice that there is no content text in the "Content" element that reads "This is a sample content". However, if I pass additional element Value inside "Content" element then it is able to output correctly.
XML Sample 2
<?xml version="1.0" encoding="UTF-8"?>
<SampleMessage type="TestType">
<Content name="TestContent"><Value>This is a sample content.</Value></Content>
</SampleMessage>
Correct Output
<?xml version="1.0" encoding="UTF-8"?>
<SampleMessage type="TestType">
<Content name="TestContent">This is a sample content.</Content>
</SampleMessage>
Any thoughts why is this?
解决方案
这已经解决了。刚刚注意到这是我其他帖子的重复,对不起。
推荐阅读
- php - laravel 显示单元测试没有断言
- sdn - 如何使用 ryu 控制器向所有交换机发送数据包?
- javascript - Firebase Admin SDK - 错误:提供给 initializeApp() 的凭据实现...未能获取有效的 Google OAuth2 访问令牌
- c++ - GTKmm Opengl 上下文未初始化
- c# - Newtonsoft.Json 未按预期序列化对象 - 错误 400
- laravel - laravel形式的坐标输入类型collective
- python - 运行 python 文件后,导入的模块未导入
- c# - 连接到在 VM 上运行的 MongoDB
- java - 获取两天之间的差异(减法)
- c# - Raspberry PI - I2C 不写入数据