如何使用jackson将java对象序列化为xml属性?

时间:2013-02-05 16:34:34

标签: java json xml-serialization jackson

有没有办法通过jackson将java var(例如int)序列化为xml属性? 我找不到任何特定的jackson或json注释(@XmlAttribute @ javax.xml.bind.annotation.XmlAttribute)实现这一点。

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;
    }
    ...
}

我想要的是什么:

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

但我得到的只是:

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

有没有办法获取属性而不是元素? 谢谢你的帮助!

2 个答案:

答案 0 :(得分:15)

好的,我找到了解决方案。

如果使用jackson-dataformat-xml,则无需注册AnnotaionIntrospector

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

缺少的TAG是

@JacksonXmlProperty(isAttribute =真)

所以只需将吸气剂更改为:

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

它工作正常。请按照以下方式:

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

  

@JacksonXmlProperty允许为其指定XML名称空间和本地名称   财产;以及是否将属性写为XML   元素或属性。

答案 1 :(得分:1)

您是否已注册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);
相关问题