我非常擅长将模型类转换为JSON数组或对象.
但是在XML方面,我是个菜鸟.
我希望我的最终输出像这样
Thanks for trying our documentation. Enjoy!
为此,我创建了一个模型类
@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之后,我的输出是
Thanks for trying our documentation. Enjoy!
我有一个额外的字符串标签.我不确定为String设置什么属性,以便它出现在主体中.还是还有其他方法?
也可以说. “ S”不大写.我怎样才能使它成为大写字母?
提前致谢
解决方法:
默认情况下,属性和公共字段将映射到元素.您要执行的操作是使用@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定义的属性.或者,您可以将注释放在吸气剂上,而忽略@XmlAccessorType
结果:
Thanks for trying our documentation. Enjoy!
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);
会给你这个输出
Thanks for trying our documentation. Enjoy!
标签:rest,jax-rs,jersey,jaxb,java
来源: https://codeday.me/bug/20191121/2049694.html