【问题标题】:Jackson XML tag and attribute with the same name具有相同名称的 Jackson XML 标记和属性
【发布时间】:2018-04-22 07:49:43
【问题描述】:

我想得到以下 XML:

<User id="two">
    <id>one</id>
</User>

我尝试为此使用 Jackson XML 映射器:

@JacksonXmlRootElement
public class User {
    private String id;

    private String attributeId;

    public User(final String id, final String attributeId) {
        this.id = id;
        this.attributeId = attributeId;
    }

    @JacksonXmlProperty(localName = "id")
    public String getId() {
        return id;
    }

    @JacksonXmlProperty(localName = "id", isAttribute = true)
    public String getAttributeId() {
        return attributeId;
    }

    public static void main(String[] args) throws IOException {
        final XmlMapper xmlMapper = new XmlMapper();
        final File file = new File("user.xml");
        final User user = new User("one", "two");

        xmlMapper.writeValue(file, user);
    }
}

但我得到的只是这个例外

java.lang.IllegalArgumentException: Conflicting getter definitions for property "id": com.sbconverter.parser.slovoed.User#getId(0 params) vs com.sbconverter.parser.slovoed.User#getAttributeId(0 params)

我可以在一个对象上使用相同的属性和标签名称吗?

【问题讨论】:

    标签: java xml serialization jackson


    【解决方案1】:

    这是一个已知问题,因此您需要针对这种情况进行额外的课程。

    在 localName (localName = "id") 的 id 前面添加一个空格可以解决问题,但更建议制作一个新 bean。

    【讨论】:

      猜你喜欢
      • 2022-08-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-06-06
      • 2021-07-23
      • 1970-01-01
      • 1970-01-01
      • 2019-04-23
      相关资源
      最近更新 更多