我正在使用Jackson库将序列化为XML。
POJO类以进行序列化:
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlElementWrapper;
import com.fasterxml.jackson.dataformat.xml.annotation.JacksonXmlProperty;
public class Row2 {
public Map<String,String> getOtherElements() {
return otherElements;
}
public void setOtherElements(Map<String,String> otherElements) {
this.otherElements = otherElements;
}
private String rn;
private int mobileNo;
@JacksonXmlElementWrapper(useWrapping = false)
private Map<String,String> otherElements;
/*Getter setters*/
}
我正在使用以下代码将此序列化为XML:
Row2 root2 = new Row2();
root2.setMobileNo(454);
Map<String,String> otherElements = new HashMap<String,String>() ;
otherElements.put("hey","there");
root2.setOtherElements(otherElements );
root2.setCities(Arrays.asList("Hum"));
JacksonXmlModule module = new JacksonXmlModule();
module.setDefaultUseWrapper(false);
XmlMapper mapper = new XmlMapper(module);
mapper.enable(SerializationFeature.INDENT_OUTPUT);
try {
String xml = mapper.writeValueAsString(root2);
System.out.println("\nXML: \n" + xml);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
我得到的输出是:
<Row2>
<rn/>
<mobileNo>454</mobileNo>
<otherElements>
<hey>there</hey>
</otherElements>
</Row2>
我希望输出,以便<hey>there</hey>
的输出中仅存在键值Map
,但是@JacksonXmlElementWrapper(useWrapping = false)
不会从输出中删除otherElements
。
所需的输出:
<Row2>
<rn/>
<mobileNo>454</mobileNo>
<hey>there</hey>
</Row2>
我尝试在@JacksonXmlElementWrapper(useWrapping = false)
类型的元素上测试 List
,它的工作原理是列表包装器不存在序列化形式。
Map
类型是否还有其他配置。文档说它适用于所有Collection
类型。
我在这里想念什么吗?