7

I am posting something like this:

{
  "stuff": [
    {
      "thingId": 1,
      "thingNumber": "abc",
      "countryCode": "ZA"
    },
    {
      "thingId": 2,
      "thingNumber": "xyz",
      "countryCode": "US"
    }
  ]
}

I can retrieve the data in the controller as follows:

@RequestMapping(value = "/stuffs", method = RequestMethod.POST)
public String invoices(@RequestBody Map<String, List <Stuff>> stuffs) {

    return "Hooray";
}

What I'd really like to do is to only pass in a List of Stuff into the controller; ie:

@RequestMapping(value = "/stuffs", method = RequestMethod.POST)
public String invoices(@RequestBody List <Stuff> stuffs) {

    return "I'm sad that this won't work.";
}

However, Jackson does not like this. The error I get is the following:

Could not read JSON document: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token\n at [Source: java.io.PushbackInputStream@2a30a2f4; line: 1, column: 1]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: Can not deserialize instance of java.util.ArrayList out of START_OBJECT token\n at [Source: java.io.PushbackInputStream@2a30a2f4; line: 1, column: 1]

I cannot send in the following (since it's not valid JSON):

    {
      [
        {
          "thingId": 1,
          "thingNumber": "abc",
          "countryCode": "ZA"
        },
        {
          "thingId": 2,
          "thingNumber": "xyz",
          "countryCode": "US"
        }
      ]
    }

I am sure that this is something simple, but I cannot distil an answer from my StackOverflow and Google searches.

Any help would be appreciated! :)

orrymr
  • 2,264
  • 4
  • 21
  • 29

2 Answers2

9

you only need to send this without the curly brackets

   [
    {
      "thingId": 1,
      "thingNumber": "abc",
      "countryCode": "ZA"
    },
    {
      "thingId": 2,
      "thingNumber": "xyz",
      "countryCode": "US"
    }
  ]

In your controller when you tell Jackson that it should be parsing a list it should be a list not an object containing a list

Amer Qarabsa
  • 6,412
  • 3
  • 20
  • 43
  • 1
    Yes! I'll choose this as accepted answer as soon as time limitation passes. You have saved me from some immense frustration! – orrymr May 16 '17 at 09:46
9

Note that if you're trying to get an array of JSON without a Java Class (the Class being "Stuff" in the OP's question) you will need to set up the Spring Boot Controller like this:

@RequestMapping(value = "/stuffs", method = RequestMethod.POST)
public String invoices(@RequestBody Map<String, Object> [] stuffs) {

    return "Hooray";
}
S. Pan
  • 619
  • 7
  • 13