仅在 XML 中忽略字段,但在 spring 引导中忽略 json 中的字段(xml 映射器)

Ignore fields only in XML but not json in spring boot (xml Mapper)

如何在使用 XMLMapper 而不是 JSON.

将 POJO 转换为 XML 时忽略某些字段
public String getXmlInString(String rootName, Object debtReport) {
    XmlMapper xmlMapper = new XmlMapper();
    return xmlMapper.writer().withRootName(rootName).withDefaultPrettyPrinter().writeValueAsString(debtReport);
}

POJOClass

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

来实现

首先使用两个“配置文件”声明视图 class - 默认(仅 Default 字段被序列化)和 json-仅(DefaultJson 字段被序列化):

public class Views {
    public static class Json extends Default {
    }
    public static class Default {
    }
}

然后用 Default-视图标记始终可见的字段,用 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>