java-XMLRootElement在jersey中将类转换为XML

我非常擅长将模型类转换为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>

我有一个额外的字符串标签.我不确定为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

结果:

<?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-HK2没有用球衣注入HttpServletRequest


下一篇:java-如何使用Jersey REST处理服务不可用的情况