Spring RestController如何接受JSON和XML? [英] How can Spring RestController accept both JSON and XML?

查看:771
本文介绍了Spring RestController如何接受JSON和XML?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a Spring controller that works great:

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

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

Here I can POST a JSON message and my widget instance gets created:

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

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

I would like this endpoint to also accept and deserialize XML widgets like so:

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

我想弄清楚:


  • 如何允许端点接受两者 JSON和XML数据,并正确地反序列化它们;和

  • 如何根据模式验证任何XML,例如 widgets.xsd

  • 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

有什么想法吗?

推荐答案

使用参数会消耗注释 @RequestMapping

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

该参数消耗一个MediaType数组

The parameter consumes takes an array of MediaType

这篇关于Spring RestController如何接受JSON和XML?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆