Div*_*ine 9 java json xml-serialization jackson
有没有办法通过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;
}
...
}
Run Code Online (Sandbox Code Playgroud)
我想要的是:
<point x="100" y="100" z="100"/>
Run Code Online (Sandbox Code Playgroud)
但我得到的只是:
<point>
<x>100</x>
<y>100</y>
<z>100</z>
</point>
Run Code Online (Sandbox Code Playgroud)
有没有办法获取属性而不是元素?感谢帮助!
Div*_*ine 15
好的,我找到了解决方案.
如果使用jackson-dataformat-xml,则无需注册AnnotaionIntrospector
File file = new File("PointTest.xml");
XmlMapper xmlMapper = new XmlMapper();
xmlMapper.writeValue(file, new Point(100, 100, 100));
Run Code Online (Sandbox Code Playgroud)
丢失的标签是
@JacksonXmlProperty(isAttribute =真)
所以只需将吸气剂更改为:
@JacksonXmlProperty(isAttribute=true)
public int getX() {
return x;
}
Run Code Online (Sandbox Code Playgroud)
它工作正常.只需按照以下方式:
https://github.com/FasterXML/jackson-dataformat-xml
@JacksonXmlProperty允许为属性指定XML名称空间和本地名称; 以及是否将属性写为XML元素或属性.