【问题标题】:Set attribute to empty xml tag using jackson-dataformat-xml library使用 jackson-dataformat-xml 库将属性设置为空 xml 标签
【发布时间】:2021-12-23 19:25:23
【问题描述】:

我有序列化为 xml 的 HashMap。 当对象为空时

HashMap<String, Object> h1 = new HashMap<>();
h1.put("test", null);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(h1));

Jackson 会生成类似的东西

<HashMap>
   <test/>
</HashMap>

所以我需要以某种方式为这个空标签添加属性

<HashMap>
   <test attribute = "something"/>
</HashMap>

有可能吗?

【问题讨论】:

    标签: java xml jackson xml-serialization


    【解决方案1】:

    你可以这样做......

    您需要使用类似薄包装器之类的东西来代替null,它会指示XmlMapper 打印此属性信息。

    这是一个解决问题的工作测试。

    public class TestXml {
        
        class NullWrapper {
            @JacksonXmlProperty(isAttribute = true)
            private String attribute = "something";
        }
    
        @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));
        }
    }
    

    输出是...

    <HashMap>
      <test attribute="something"/>
    </HashMap>
    

    这能解决您的问题吗?在 cmets 中告诉我。

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-25
    • 1970-01-01
    • 2015-09-30
    • 1970-01-01
    • 1970-01-01
    • 2019-11-09
    • 2017-01-11
    • 2015-05-19
    相关资源
    最近更新 更多