How to consume different request bodies in one endpoint?

Viewed 571

I need to build a service that needs to consume different xmlTypes in request body of one endpoint.

To do so, I've implemented this:

    @PostMapping(value="/one")
    public ResponseEntity<?> result(
            String xmlType,
            @RequestBody Object body
    ) {
        Employe employee = null; // employee object that is generated by xsd file.
        Profile profile = null; // profile object that is generated by xsd file.
        if (body instanceof Employe) {
            employee = (Employe) body;
        } else if (body instanceof Profile) {
            profile = (Profile) body;
        }
        
        // business logic 

        return ResponseEntity.accepted().build();
    }

but by this implementation, I'm getting Unsupported Media Type error.

Example usage of the service;

  • url: '/domain/one?xmlType=Profile', body(requestBody): <Profile></Profile>
  • url: '/domain/one?xmlType=Employee', body(requestBody): <Employee></Employee>

When I use the specific Object it works, but I couldn't implement the generic version. So, how can I achieve this feature?

2 Answers

I'd use two methods and narrow the request mapping thanks to params:

@PostMapping(value = "/one", params = "xmlType=Profile")
public ResponseEntity<?> postProfile(@RequestBody Profile body) {
    ...
}

@PostMapping(value = "/one", params = "xmlType=Employee")
public ResponseEntity<?> postEmployee(@RequestBody Employee body) {
    ...
}

That's actually a good question.

How about creating an empty DTO class with the @JsonIgnoreProperties(ignoreUnknown = true) annotation?

Related