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