javajacksonspring-webjackson-dataformat-xml

Jackson unmarshalling succeeds even though wrong XML root element


Using Spring Boot (2.1.4) and Jackson (2.9.8), I'm writing an API that consumes and produces XML, using @RestController and @RequestBody.

Consuming XML works, but it works a bit too well: When the root element does not match that of my Java object (annotated with @JacksonXmlRootElement localName), it still manages to unmarshall the object.

The rest controller looks like this:

@RestController
@RequestMapping(value = "api", produces = MediaType.APPLICATION_XML_VALUE, consumes = MediaType.APPLICATION_XML_VALUE)
public class PutawayApiController extends BaseController {

    private final ModelSampleService sampleService;

    @Autowired
    public PutawayApiController(ModelSampleService sampleService) {
        this.sampleService = sampleService;
    }

    @PostMapping(value = "/putaway_close")
    public PutawayCloseResponse putawayClose(@RequestBody PutawayCloseRequest request) {
        return sampleService.putawayCloseResponse();
    }

}

With the request object being:

@Data
@EqualsAndHashCode(callSuper = false)
@JacksonXmlRootElement(localName = "putawayCloseRequest")
public class PutawayCloseRequest extends BaseRequest {

    private String shipmentRef;

}

and it inherits from:

@Data
public abstract class BaseRequest {

    private String userId;

}

When performing the following call in Postman, it triggers my debug point as displayed in the following image: Unmarshalling triggered although incorrect root element name

Why does it unmarshall even though the root element is clearly not what I configured? Is there way to enable rejecting the unmarshalling when the root element does not match?

Thanks in advance.


Solution

  • Because the documentation, i.e. the javadoc of @JacksonXmlRootElement says:

    Annotation that can be used to define name of root element used for the root-level object when serialized, which normally uses name of the type (class).

    It never claims to use it for validating when deserializing.