is there a way to serialize a java var (e.g. int) via jackson as an xml attribute?
I can not find any spezific jackson or json annotation (@XmlAttribute
@javax.xml.bind.annotation.XmlAttribute) to realize this.
e.g.
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:
but all I got is:
100
100
100
Is there a way to get attributes instead of elements?
Thanks for help!
解决方案
Okay I found a solution.
It wasn't necessary to register an 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));
The missing TAG was
@JacksonXmlProperty(isAttribute=true)
so just change the getter to:
@JacksonXmlProperty(isAttribute=true)
public int getX() {
return x;
}
and it works fine. Just follow this how to:
@JacksonXmlProperty allows specifying XML namespace and local name for
a property; as well as whether property is to be written as an XML
element or attribute.