问题描述
如何在使用 XMLMapper
而不是在 JSON 中将 POJO 转换为 XML 时忽略某些字段。
public String getXmlInString(String rootName,Object debtReport) {
XmlMapper xmlMapper = new XmlMapper();
return xmlMapper.writer().withRootName(rootName).withDefaultPrettyPrinter().writeValueAsstring(debtReport);
}
POJO 类
Class Employee {
Long id;
String name;
LocalDate dob;
}
JSON 格式的预期输出
{
"id": 1,"name": "Thirumal","dob": "02-04-1991"
}
XML 中的预期输出(需要忽略 ID
)
<Employee>
<name>Thirumal</name>
<dob>02-04-1991</dob>
</Employee>
解决方法
您可以使用 JsonView
首先声明具有两个“配置文件”的 Views 类 - 默认(只有 Default
字段被序列化)和 json-only(Default
和 Json
字段都被序列化):
public class Views {
public static class Json extends Default {
}
public static class Default {
}
}
然后用 Default
-view 标记始终可见的字段,用 Json
视图标记 ID 字段:
public class Employee {
@JsonView(Views.Json.class)
Long id;
@JsonView(Views.Default.class)
String name;
@JsonView(Views.Default.class)
String dob;
}
然后指示映射器在序列化期间尊重给定的适当视图:
@Test
public void test() throws JsonProcessingException {
Employee emp = new Employee();
emp.id = 1L;
emp.name = "John Doe";
emp.dob = "1994-03-02";
// JSON with ID
String json = new ObjectMapper()
.writerWithView(Views.Json.class)
.writeValueAsString(emp);
System.out.println("JSON: " + json);
// XML without ID
String xml = new XmlMapper()
.writerWithView(Views.Default.class)
.writeValueAsString(emp);
System.out.println("XML: " + xml);
}
最后输出是:
JSON: {"id":1,"name":"John Doe","dob":"1994-03-02"}
XML: <Employee><name>John Doe</name><dob>1994-03-02</dob></Employee>