杰克逊JSON XML - 序列化为XML时的不同名称

4

当我的元素被序列化为XML时,我希望它有一个不同的名称(例如"fooXml"),而在JSON中则有不同的名称(例如"fooJson")。是否可能实现这种需求?

我使用XML注解如下:

@XmlElements({
    @XmlElement(type = Foo.class, name = "fooXml"),
    })
    private SortedSet<Foo> fooSet;

我已经尝试使用@JsonProperty,但没有成功。

我还尝试将它导出到getter方法中,例如:

@XmlElement(type = Foo.class, name = "fooXml")
@JsonProperty(value = "fooJson")
public List<Foo> getFooList() {
    return new ArrayList<>(fooSet);
}

但它总是忽略JSON注释并将其序列化为XML格式(fooXml名称)。
我该怎么做?
编辑:我正在使用Jersey-json。

它是将数据序列化为XML而不是JSON,还是只序列化为JSON并使用XML名称? - Core_F
@Feroc JSON使用XML名称。 - Greg Witczak
1个回答

5

好的,我有同样的需求并找到了一个适用的解决方案:

import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;

@JsonProperty("MyJsonName")
@JacksonXmlProperty(localName = "MyXmlName")
private MyProperty myProperty;

这对我有用,而且我的属性将在 Json 中的“ MyJsonName”字段和 XML 中的“ MyXmlName”中。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接