Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jackson cant instantiate ArrayList

I want to send the following POST request:

POST: /api/test
{
   "words": ["running", "testing", "and"]
}

My controller looks as follows:

@RequestMapping(value={"/api/test"}, method=RequestMethod.POST)
@ResponseBody
public ResponseEntity<Text> getWords(@RequestBody Words words) {
    // Do something with words...
    return new ResponseEntity<Text>(new Text("test"), HttpStatus.OK);
}

The Words class:

public class Words {

    private List<String> words;

    public Words(List<String> words) {
        this.words = words;
    }

    public List<String> getWords() {
        return words;
    }
}

When sending Strings instead of the List it works fine however with the List I get the following error:

Could not read document:
No suitable constructor found for type [simple type, class api.models.tokenizer.Words]: can not instantiate from JSON object (need to add/enable type information?)\n at [Source: java.io.PushbackInputStream@60f2a08; line: 2, column: 5]; nested exception is com.fasterxml.jackson.databind.JsonMappingException: No suitable constructor found for type [simple type, class api.models.tokenizer.Words]: can not instantiate from JSON object (need to add/enable type information?)\n at [Source: java.io.PushbackInputStream@60f2a08; line: 2, column: 5]
like image 819
fwind Avatar asked Jan 23 '26 12:01

fwind


1 Answers

By default Jackson creates instance of class using default constructor. You do not have one. So, either add constructor

public Words() {}

Or mark existing constructor using annotation @JsonCreator:

@JsonCreator
public Words(@JsonProperty("words") List<String> words) {
    this.words = words;
}
like image 66
AlexR Avatar answered Jan 25 '26 02:01

AlexR



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!