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

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

我想要的:

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

但我得到的只是:

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

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

最佳答案

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

如果您使用 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 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.

关于java - 如何使用 jackson 将 java 对象序列化为 xml 属性?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14712312/

相关文章:

java - ==如何比较内存位置?

java - 我不能在 Java 11 中使用 @PostConstruct 和 @PostDestroy

javascript - 主干模型、JSON 和 HTML 表单

json - updateSearchResultsForSearchController JSON

c# - 带有 xmlSerializer 的 UWP - System.InvalidOperationException : Unable to generate a temporary class (result=1) compile error

java - EclipseLink 在 OneToMany 关系中找不到实体

java - 如何使用 Java 创建一个简单的 Web 应用程序来测试我的 Web 服务

javascript - Json 返回的 JQuery 更新选项

java - 将 Java 对象序列化为 xml 并返回(XML 配置)

c# - XSD.exe 不强制执行 minOccurs