简体   繁体   中英

How to dynamically add xml element to a java JAXRS representation?

Say I have a java class that is a representation of a "Dog" with attrbutes "Color" and "Type" marked up with @XmlElement and @XmlRootElement tags. How do I add a "Age" xml element to this JAXRS based class programmatically without modifying my Dog class with @XmlAttribute(name="Age") ?

Assume I have the representation:

DogRepClass adog = new DogRepClass();

You'd have to create your own MessageBodyWriter but rather than make your own from scratch, you can extend it to process some custom annotations that your message body writer can recognize via the .entity(Object, Annotation[]) method. That way you just add on something specific for your needs

You can define your own MessageBodyWriter (http://jsr311.java.net/nonav/javadoc/javax/ws/rs/ext/MessageBodyWriter.html) only for this particular type. It can marshall your instance into DOM, modify it and serialize afterwards. Not nice nor elegant, but it will work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM