57

I've implemented a Spring RESTful web service. Using Jackson JSON for Object Mapping. I have a method that accepts two parameters.

public Person createPerson(
    @RequestBody UserContext userContext,
    @RequestBody Person person)

How would the client construct a request where in multiple JSON objects are to be passed in the body?

Is this possible?

-- Sri

Sean Patrick Floyd
  • 274,607
  • 58
  • 445
  • 566
Sri
  • 5,543
  • 10
  • 45
  • 68

1 Answers1

72

I'm pretty sure that won't work. There may be a workaround, but the much easier way would be to introduce a wrapper Object and change your signature:

public class PersonContext{
    private UserContext userContext;
    private Person person;
    // getters and setters
}


public Person createPerson(@RequestBody PersonContext personContext)
Sean Patrick Floyd
  • 274,607
  • 58
  • 445
  • 566
  • Thanks, I'm considering a wrapper Array as the last resort. What is the work around you were referring to? – Sri Apr 20 '11 at 07:13
  • 1
    @Srirangan: the workarround is the PersonContext class - it is some kind of DTO – Ralph Apr 20 '11 at 07:24
  • @Srirangan I said there *may* be a workaround. I am not aware of one myself – Sean Patrick Floyd Apr 20 '11 at 07:32
  • 12
    I feel stupid for asking this question. How can an HTTP request have multiple "bodies". Argh. 2011-me was stupid. – Sri May 03 '14 at 07:43
  • 27
    @Srirangan don't worry, we've all been there :-) – Sean Patrick Floyd May 05 '14 at 07:32
  • 1
    @Sri, nevertheless thank you for asking it, it helps us that have to pick up Spring quickly because of being thrown in at the deep end. [This question](https://stackoverflow.com/q/12893566/2114313) is similar and has a more detailed answer, you might want to link. – fr13d Aug 20 '19 at 07:53
  • Is it be possible to set a custom Jackson deserializer for an object/instance variables inside of PersonContext? – nonNumericalFloat Feb 02 '21 at 11:48
  • 1
    @nonNumericalFloat sure, just annotate any field with [`@JsonDeserialize`](https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/annotation/JsonDeserialize.html) with a custom [`JsonDeserializer`](https://fasterxml.github.io/jackson-databind/javadoc/2.8/com/fasterxml/jackson/databind/JsonDeserializer.html) implementation – Sean Patrick Floyd Feb 02 '21 at 18:25
  • @SeanPatrickFloyd didn't realize that it was this easy. Thank you! :) – nonNumericalFloat Feb 02 '21 at 19:00