【问题标题】:Set attributes to xml tag without POJO using jackson-dataformat-xml library使用 jackson-dataformat-xml 库将属性设置为没有 POJO 的 xml 标签
【发布时间】:2021-11-11 14:14:52
【问题描述】:

我使用 HashMap 将其序列化为 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>

除了自定义序列化器,还有什么解决方法吗?

【问题讨论】:

    标签: java xml jackson xml-serialization


    【解决方案1】:

    你可以这样做

    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));
        }
    }
    

    【讨论】:

    猜你喜欢
    • 2021-12-23
    • 2020-11-25
    • 1970-01-01
    • 1970-01-01
    • 2023-02-05
    • 2015-05-19
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多