【问题标题】:How to serialize java object as xml attribute with jackson?如何使用jackson将java对象序列化为xml属性?
【发布时间】:2013-01-20 15:53:19
【问题描述】:

有没有办法通过 jackson 将 java var(例如 int)序列化为 xml 属性? 我找不到任何特定的杰克逊或 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>

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

【问题讨论】:

  • int类型没有问题。我试过什么,我只是得到了 xml 元素而不是属性。

标签: java json xml-serialization jackson


【解决方案1】:

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

如果您使用 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 允许为 财产;以及是否将属性写为 XML 元素或属性。

【讨论】:

    【解决方案2】:

    你注册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);
    

    【讨论】:

      猜你喜欢
      • 2018-01-27
      • 2018-01-04
      • 2021-10-18
      • 1970-01-01
      • 2020-04-11
      • 2017-09-10
      • 1970-01-01
      • 2011-12-21
      • 1970-01-01
      相关资源
      最近更新 更多