有没有办法通过 jackson 将 java var(例如 int)序列化为 xml 属性? 我找不到任何特殊的 jackson 或 json 注释(@XmlAttribute @javax.xml.bind.annotation.XmlAttribute) 来实现这一点。
例如
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;
}
...
}
我想要的:
<point x="100" y="100" z="100"/>
但我得到的只是:
<point>
<x>100</x>
<y>100</y>
<z>100</z>
</point>
有没有办法获取属性而不是元素? 感谢您的帮助!
最佳答案
好的,我找到了解决方案。
如果您使用 jackson-dataformat-xml,则无需注册 AnnotaionIntrospector
File file = new File("PointTest.xml");
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(file, new Point(100, 100, 100));
缺少的标签是
@JacksonXmlProperty(isAttribute=true)
所以只需将 getter 更改为:
@JacksonXmlProperty(isAttribute=true)
public int getX() {
return x;
}
而且效果很好。只需按照以下方法操作即可:
https://github.com/FasterXML/jackson-dataformat-xml
@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.
关于java - 如何使用 jackson 将 java 对象序列化为 xml 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14712312/