MediaType.APPLICATION_XML_VALUE issue

570 views Asked by At

I have a method that is configured to return either JSON or XML output using Spring boot 2.6.2. while it works fine for JSON, while trying to return XML output, it gives an exception - org.springframework.web.HttpMediaTypeNotAcceptableException

Provided below is the code example

    @PostMapping (
            produces = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE},
            consumes = {MediaType.APPLICATION_JSON_VALUE, MediaType.APPLICATION_XML_VALUE})
    public ResponseEntity<CreateUserResponseModel> createUser(@Valid @RequestBody CreateUserRequestModel userDetails) {

        ModelMapper modelMapper = new ModelMapper();
        modelMapper.getConfiguration().setMatchingStrategy(MatchingStrategies.STRICT);

        UserDTO userDTO = modelMapper.map(userDetails, UserDTO.class);
        UserDTO createdUser = userService.createUser(userDTO);

        CreateUserResponseModel returnValue = modelMapper.map(createdUser, CreateUserResponseModel.class);

        return ResponseEntity.status(HttpStatus.CREATED).body(returnValue);
    }

The following has been configured in the POM file

        <dependency>
            <groupId>com.fasterxml.jackson.dataformat</groupId>
            <artifactId>jackson-dataformat-xml</artifactId>
        </dependency>

Configuration in Postman to call a POST method is as follows; Headers:

1. Accept: application/XML
2. Content-Type: application/JSON

When I run this for Accept: application/JSON, it works fine. However, when the Accept parameter is changed to application/XML, it gives an exception org.springframework.web.HttpMediaTypeNotAcceptableException

Any suggestions on what needs to change in the annotation or code?

0

There are 0 answers