java - 使用 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>
除了自定义序列化程序之外还有其他解决方法吗?
解决方案
你可以这样做
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));
}
}
推荐阅读
- python - 使用 pandas 将列附加到列
- c# - 控制请求对象解构的选项
- swift - 具有类绑定约束的泛型类不能通过类绑定协议参数化
- python - 如何创建逻辑来在熊猫中进行值映射?
- python - 为什么我的熊猫数据框使用这么多内存?
- elixir - 在 Elixir 中,将测试文件与相关模块放在一起
- c# - Angular:无法通过 HttpResponse 返回自定义错误消息
- c# - 在分支之间转换时生成错误:您的项目未引用“.NETFramework,Version=v4.7.2”框架
- python - 抓取linkedin新闻提要
- docker - Docker 容器以代码 0 退出