Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson XML Annotations: String element with attribute

Tags:

java

xml

jackson

I can't seem to find a way to make a Pojo Using the jackson-xml annotations that would generate xml like the following:

<Root>     <Element1 ns="xxx">         <Element2 ns="yyy">A String</Element2>     </Element1> </Root> 

The closest I can seem to come is the following:

Root POJO:

public class Root {     @JacksonXmlProperty(localName = "Element1")     private Element1 element1;      public String getElement1() {         return element1;     }      public void setElement1(String element1) {         this.element1 = element1;     } } 

Element1 POJO:

public class Element1 {     @JacksonXmlProperty(isAttribute = true)     private String ns = "xxx";     @JacksonXmlProperty(localName = "Element2")     private Element2 element2;      public String getElement2() {         return element2;     }      public void setElement2(String element2) {         this.element2 = element2;     } } 

Element2 POJO:

public class Element2 {     @JacksonXmlProperty(isAttribute = true)     private String ns = "yyy";     private String value;      public String getValue() {         return value;     }      public void setValue(String value) {         this.value = value;     } } 

But this returns back the following:

<Root>     <Element1 ns="xxx">         <Element2 ns="yyy"><value>A String</value></Element2>     </Element1> </Root> 

The element tags around "A String" I do not want to display.

like image 895
jtyler Avatar asked Nov 07 '13 21:11

jtyler


People also ask

Can ObjectMapper be used for XML?

Configuration of XML Mapper Object XmlMapper extends ObjectMapper . Therefore, you can use XML in the same way that you use ObjectMapper . For example, register the Java 8 modules to enable the feature of parameter names, Java 8 time, and Java 8 data types.

Can Jackson use JAXB annotations?

Supporting JAXB AnnotationsThe Jackson XML module also has the ability to support the standard JAXB annotations on our beans – instead of needing the Jackson specific ones.

What is Jackson Dataformat XML?

Package. Description. com.fasterxml.jackson.dataformat.xml. Package that contains XML-based backends which can serialize POJOs to and deserialize from XML, using Stax XML parsers and generators for XML processing and mostly standard Jackson data binding otherwise.


1 Answers

You should use JacksonXmlText annotation for value field.

public class Element2  {     @JacksonXmlProperty(isAttribute = true)     private String ns = "yyy";     @JacksonXmlText     private String value;      public String getValue() {         return value;     }      public void setValue(String value) {         this.value = value;     } }   

then XML will looks like

<Root>     <Element1 ns="xxx">         <Element2 ns="yyy">A String</Element2>     </Element1> </Root> 
like image 186
Ilya Avatar answered Sep 21 '22 08:09

Ilya