小编典典

Spring RestController如何接受JSON和XML?

spring-mvc

我有一个很棒的Spring控制器:

@RestController
@RequestMapping(value = "/widgets")
class WidgetController {
    @RequestMapping(method = RequestMethod.POST)
    WidgetResponse createWidget(@Valid @RequestBody Widget widget) {
        // ...
    }
}

在这里,我可以发布JSON消息,并创建我的小部件实例:

{
  "name" : "Widget1",
  "type" : "spinning",
  "isFizz" : true
}

我希望该端点也接受和反序列化XML小部件,如下所示:

<widget name="Widget1">
  <type>spinning</type>
  <isFizz>false</isFizz>
</widget>

我试图找出:

  • 如何让端点接受 两个 JSON和XML数据,并正确反序列化他们。和
  • 如何根据模式验证任何XML,例如 widgets.xsd

有任何想法吗?


阅读 1163

收藏
2020-06-01

共1个答案

小编典典

consumes注解的参数@RequestMapping

@RequestMapping(value = "/widgets",consumes={MediaType.APPLICATION_JSON_VALUE,MediaType.APPLICATION_XML_VALUE})
WidgetResponse createWidget(@Valid @RequestBody Widget widget){
///
{

参数消耗一个MediaType数组

2020-06-01