首页 > 解决方案 > 使用 jackson-dataformat-xml 库将属性设置为没有 POJO 的 xml 标签

问题描述

我使用 HashMap<String, Object> 将其序列化为 xml:

var mapper = new XmlMapper();
HashMap<String, Object> hm = new HashMap<>();
hm.put("header", "value");
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(hm));

输出

<HashMap>
  <header>value</header>
</HashMap>

问题是我需要将未知的直到运行时数量的属性添加到标题中。

<HashMap>
  <header attr1= "text" attr2 = "another text" >value</header>
</HashMap>

除了自定义序列化程序之外还有其他解决方法吗?

标签: javaxmljacksonxml-serialization

解决方案


你可以这样做

public class TestXml {
    
    class HeaderWrapper {
        @JacksonXmlProperty(isAttribute = true)
        private String attr1 = "text";

        @JacksonXmlProperty(isAttribute = true)
        private String attr2 = "another text";
    
        private String header = "value"
    }

    @Test
    void test() throws JsonProcessingException {
        var mapper = new XmlMapper();
        var h1 = new HashMap<>();
        h1.put("test", new NullWrapper());
        System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(h1));
    }
}

推荐阅读