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

How to ignore some fields while converting POJO to XML using XMLMapper but not in JSON.

public String getXmlInString(String rootName, Object debtReport) {
    XmlMapper xmlMapper = new XmlMapper();
    return xmlMapper.writer().withRootName(rootName).withDefaultPrettyPrinter().writeValueAsString(debtReport);
}

POJO Class

Class Employee {
    Long id;
    String name;
    LocalDate dob;
}

The expected output in JSON

{
"id": 1,
"name": "Thirumal",
"dob": "02-04-1991"
}

The expected output in XML (Need to ignore ID)

<Employee>
<name>Thirumal</name>
<dob>02-04-1991</dob>
</Employee>

Answer

You can achieve that using JsonView

First declare Views class with two “profiles” – default (only Default fields are serialized) and json-only (both Default and Json fields are serialized):

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

Then mark always visible fields with Default-view and ID field with Json view:

public class Employee {
    @JsonView(Views.Json.class)
    Long id;

    @JsonView(Views.Default.class)
    String name;

    @JsonView(Views.Default.class)
    String dob;
}

Then instruct mapper to respect given appropriate view during serialization:

@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);
}

Finally the output is:

JSON: {"id":1,"name":"John Doe","dob":"1994-03-02"}
XML: <Employee><name>John Doe</name><dob>1994-03-02</dob></Employee>

Leave a Reply

Your email address will not be published. Required fields are marked *