8

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

2 Answers 2

10

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

Sign up to request clarification or add additional context in comments.

1 Comment

Yes! I'll choose this as accepted answer as soon as time limitation passes. You have saved me from some immense frustration!
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";
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.