我有一个只包含一个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;
}
}
我尝试用杰克逊生成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元素?
答案 0 :(得分:2)
使用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()));
答案 1 :(得分:0)
我认为最好的选择是使用@JsonAnyGetter
上方的getMap2()
注释。是的,它的json注释,但你必须将它用于xml和json https://github.com/FasterXML/jackson-dataformat-xml#additional-annotations
public static class Application {
private Map<String,Object> map2;
@JsonAnyGetter
public Map<String, Object> getMap2() {
return Collections.unmodifiableMap(map2);
}
public void setMap2(Map<String, Object> map2) {
this.map2 = map2;
}
// if you need deserialization
@JsonAnySetter
public void setMap2(String key, Object value) {
map2.put(key, value);
}
}
2-nd Option(如果你可以改变你的结构)是使用
public static class Application extends HashMap<String,Object> {}
// or if you want to change map class name:
@JsonRootName("Application")
public static class MyMap extends HashMap<String,Object>{}