gpt4 book ai didi

java - 使用 Jackson 将带有 HashMap 的对象转换为 XML

转载 作者:行者123 更新时间:2023-11-30 08:37:08 25 4
gpt4 key购买 nike

我有一个只包含一个 hasmap 类型属性的对象。

public class Application {

private Map<String,Object> map2;

public Map<String, Object> getMap2() {
return Collections.unmodifiableMap(map2);
}

public void setMap2(Map<String, Object> map2) {
this.map2 = map2;
}
}

然后我尝试使用 Jackson 生成 XML:

Map<String,Object> map = new HashMap<String, Object>();
map.put("key1", "value1");
map.put("key2", "value2");

XmlMapper xmlMapper = new XmlMapper();
xmlMapper.configure( ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true );
System.out.println(xmlMapper.writeValueAsString(app));

结果是:

<?xml version='1.0' encoding='UTF-8'?>
<Application>
<Map2>
<key1>value1</key1>
<key2>value2</key2>
</Map2>
</Application>

但我只想:

<?xml version='1.0' encoding='UTF-8'?>
<Application>
<key1>value1</key1>
<key2>value2</key2>
</Application>

如何删除 Map2 元素?

最佳答案

使用 HashMap 而不是整个类。喜欢

public class AppDao {

private Map<String,Object> Application;

public Map<String, Object> getMap2() {
return Collections.unmodifiableMap(map2);
}

public void setMap2(Map<String, Object> Application) {
this.Application = Application;
}
public Map<String,Object> getMap2(){
return Application;
}
}

现在使用hashmap生成XML

xmlMapper.configure( ToXmlGenerator.Feature.WRITE_XML_DECLARATION, true );
System.out.println(xmlMapper.writeValueAsString(app.getMap2()));

关于java - 使用 Jackson 将带有 HashMap 的对象转换为 XML,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37438132/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com