我非常擅长将模型类转换为 JSON 数组或对象。
但在 XML 方面我是个菜鸟。
我希望我的最终输出是这样的
<Response>
<Say voice="alice">Thanks for trying our documentation. Enjoy!</Say>
</Response>
为了实现它,我创建了一个模型类
@XmlRootElement(name = "Response")
public class Response {
private Say say = new Say();
public Say getSay() {
return say;
}
public void setSay(Say say) {
this.say = say;
}
@XmlRootElement(name = "Say")
static class Say {
@XmlAttribute
private String voice = "alice";
private String string = "Thanks for trying our documentation. Enjoy!";
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
}
}
现在用 Jersey 将它转换为 XML 后,我的输出是
<Response>
<say voice="alice">
<string>Thanks for trying our documentation. Enjoy!</string>
</say>
</Response>
我有一个额外的字符串标签。我不确定要为字符串设置什么属性,以便它出现在正文中。?还是有其他办法?
也为说。 “S”没有大写。我怎样才能让它成为大写字母?
提前致谢
最佳答案
默认情况下,属性和公共(public)字段将映射到元素。你想要做的是使用 @XmlValue
将字段映射到元素的值。
@XmlRootElement(name = "Say")
@XmlAccessorType(XmlAccessType.FIELD)
static class Say {
@XmlAttribute
private String voice = "alice";
@XmlValue
private String string = "Thanks for trying our documentation. Enjoy!";
public String getString() {
return string;
}
public void setString(String string) {
this.string = string;
}
}
注意 @XmlAccessorType(XmlAccessType.FIELD)
的使用。这样默认行为就不会“双重”尝试映射由 getter 和 setter 定义的属性。或者,您可以将注释放在 getter 上,并省略 @XmlAccessorType
结果:
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Response>
<say voice="alice">Thanks for trying our documentation. Enjoy!</say>
</Response>
public class ResponseTest {
public static void main(String[] args) throws Exception {
JAXBContext context = JAXBContext.newInstance(Response.class);
Marshaller marshaller = context.createMarshaller();
marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
Response response = new Response();
marshaller.marshal(response, System.out);
}
}
更新
but can i know why the 'S' in Say is not capitalised even though
@XmlRootElement(name = "Say")
is specified?
您需要在属性上使用 @XmlElement(name = "Say")
指定名称。如果您不这样做,默认命名将生效。
@XmlElement(name = "Say")
public Say getSay() {
return say;
}
XmlRootElement(name = "Say")
仅适用于元素用作根元素的情况。比如这个:
Response.Say response = new Response.Say();
marshaller.marshal(response, System.out);
会给你这个输出
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Say voice="alice">Thanks for trying our documentation. Enjoy!</Say>
关于java - XMLRootElement 在 Jersey 中将类转换为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26334733/