如何使用jackson将java对象序列化为xml属性? [英] How to serialize java object as xml attribute with jackson?

查看:1682
本文介绍了如何使用jackson将java对象序列化为xml属性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

is there a way to serialize a java var (e.g. int) via jackson as an xml attribute? I can not find any spezific jackson or json annotation (@XmlAttribute @javax.xml.bind.annotation.XmlAttribute) to realize this.

例如。

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>

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

Is there a way to get attributes instead of elements? Thanks for help!

推荐答案

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

Okay I found a solution.

如果你使用jackson-dataformat-xml,没有必要注册AnnotaionIntrospector

It wasn't necessary to register an AnnotaionIntrospector if you use jackson-dataformat-xml

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

缺少的TAG是

@JacksonXmlProperty (isAttribute = true)

@JacksonXmlProperty(isAttribute=true)

所以只需将getter更改为:

so just change the getter to:

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

并且工作正常。请按照以下说明:

and it works fine. Just follow this how to:

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


@JacksonXmlProperty允许为$指定XML名称空间和本地名称b $ ba财产;以及是否将属性写为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.

这篇关于如何使用jackson将java对象序列化为xml属性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆