Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Post a JSON Array into Spring Boot RestController

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! :)

like image 435
orrymr Avatar asked May 16 '17 09:05

orrymr


1 Answers

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

like image 103
Amer Qarabsa Avatar answered Sep 18 '22 14:09

Amer Qarabsa