问题
I have a Spring controller that works great:
@RestController
@RequestMapping(value = "/widgets")
class WidgetController {
@RequestMapping(method = RequestMethod.POST)
WidgetResponse createWidget(@Valid @RequestBody Widget widget) {
// ...
}
}
Here I can POST a JSON message and my widget instance gets created:
{
"name" : "Widget1",
"type" : "spinning",
"isFizz" : true
}
I would like this endpoint to also accept and deserialize XML widgets like so:
<widget name="Widget1">
<type>spinning</type>
<isFizz>false</isFizz>
</widget>
I'm trying to figure out:
- How to allow the endpoint to accept both JSON and XML data, and deserialize them properly; and
- How to validate any XML against a Schema, such as
widgets.xsd
Any ideas?
回答1:
With the parameter consumes of annotation @RequestMapping
@RequestMapping(value = "/widgets",consumes={MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_XML_VALUE})
WidgetResponse createWidget(@Valid @RequestBody Widget widget){
///
{
The parameter consumes takes an array of MediaType
来源:https://stackoverflow.com/questions/44597140/how-can-spring-restcontroller-accept-both-json-and-xml