Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can Spring RestController accept both JSON and XML?

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?

like image 998
smeeb Avatar asked Nov 15 '25 22:11

smeeb


1 Answers

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

like image 199
Christian Amani Avatar answered Nov 17 '25 18:11

Christian Amani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!