How to serialize java object as xml attribute using jackson?

Is there a way to serialize java var (e.g. int) via jackson as an xml attribute? I cannot find any special jackson or json annotation (@XmlAttribute @ javax.xml.bind.annotation.XmlAttribute) to implement this.

eg.

public class Point { private int x, y, z; public Point(final int x, final int y, final int z) { this.x = x; this.y = y; this.z = z; } @javax.xml.bind.annotation.XmlAttribute public int getX() { return x; } ... } 

What I want:

 <point x="100" y="100" z="100"/> 

but all i have is:

 <point> <x>100</x> <y>100</y> <z>100</z> </point> 

Is there a way to get attributes instead of elements? Thanks for the help!

+8
java json jackson xml-serialization
source share
2 answers

Ok, I found a solution.

No need to register AnnotaionIntrospector if you use jackson-dataformat-xml

 File file = new File("PointTest.xml"); XmlMapper xmlMapper = new XmlMapper(); xmlMapper.writeValue(file, new Point(100, 100, 100)); 

Invalid TAG was

@JacksonXmlProperty (isAttribute = true)

just change the getter to:

 @JacksonXmlProperty(isAttribute=true) public int getX() { return x; } 

and it works great. Just follow these steps:

https://github.com/FasterXML/jackson-dataformat-xml

@JacksonXmlProperty allows you to specify the XML namespace and local name for real estate; as well as how a property should be written as an XML element or attribute.

+13
source share

Have you registered JaxbAnnotationIntrospector ?

 ObjectMapper mapper = new ObjectMapper(); AnnotationIntrospector introspector = new JaxbAnnotationIntrospector(); // make deserializer use JAXB annotations (only) mapper.getDeserializationConfig().setAnnotationIntrospector(introspector); // make serializer use JAXB annotations (only) mapper.getSerializationConfig().setAnnotationIntrospector(introspector); 
+1
source share

All Articles