我有HashMap,它被序列化为xml。当对象为空时
HashMap<String, Object> h1 = new HashMap<>();
h1.put("test", null);
System.out.println(mapper.writerWithDefaultPrettyPrinter().writeValueAsString(h1));杰克逊产生了这样的东西
<HashMap>
<test/>
</HashMap>所以我需要在这个空标签中添加属性
<HashMap>
<test attribute = "something"/>
</HashMap>有可能吗?
发布于 2021-11-11 10:17:21
你可以这样做..。
而不是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>这能解决你的问题吗?在评论中告诉我。
https://stackoverflow.com/questions/69926101
复制相似问题