How can Spring RestController accept both JSON and XML?

喜夏-厌秋 提交于 2019-12-11 05:36:13

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!