【问题标题】:Ignore fields only in XML but not json in spring boot (xml Mapper)仅在 XML 中忽略字段,但在 Spring Boot(xml 映射器)中不忽略 json
【发布时间】:2021-06-22 23:40:25
【问题描述】:

如何在使用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>

【问题讨论】:

    标签: java xml spring-boot jackson fasterxml


    【解决方案1】:

    您可以使用JsonView 实现这一目标

    首先用两个“配置文件”声明 Views 类 - 默认(仅Default 字段被序列化)和 json-only(DefaultJson 字段都被序列化):

    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>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-07-12
      • 2020-10-26
      • 2015-11-07
      • 1970-01-01
      • 2015-07-05
      • 2017-05-03
      • 2016-08-01
      相关资源
      最近更新 更多