selvi
selvi

Reputation: 1477

How to define RequestBody in controller as list, I am getting 500 error

I want to pass search input as list, Refer the below code and payload which i tried, I am getting parser errror.

// code in searchinput

public class SearchInput {
    private List<SearchCriteria> criterias;

}

// code in search criteria

public class SearchCriteria {
    private String key;
    private String operation;
    private String value;
}

//code for controller

@PostMapping("/searchhh")
    public List<Profile> findProfiles(@RequestBody SearchInput input) {
        List<SearchCriteria> criterias = input.getCriterias();
                System.out.println("criterias=" + criterias);
        
        return null;
    }

// payload which I tired

URL:
http://localhost:5555/matrimony/api/v1/profiles/searchhh

Request body:
[
  {
    "key": "g",
    "operation": "eq",
    "value": "m"
  },
  {
    "key": "name",
    "operation": "like",
    "value": "Rani"
  },
  {
    "key": "sh",
    "operation": "eq",
    "value": "Never"
  }
]

Response:
{
    "message": "JSON parse error: Cannot deserialize instance of `com.model.SearchInput` out of START_ARRAY token; nested exception is com.fasterxml.jackson.databind.exc.MismatchedInputException: Cannot deserialize instance of `com.model.SearchInput` out of START_ARRAY token\n at [Source: (PushbackInputStream); line: 1, column: 1]",
    "status": 500,
    "timestamp": "2021-01-21T11:31:48.228796"
}

Upvotes: 2

Views: 267

Answers (2)

Ryuzaki L
Ryuzaki L

Reputation: 40078

The above payload which you are passing as request body represents array of SearchCriteria objects, so you can parse that json directly into List<SearchCriteria> and no need of SearchInput class

@PostMapping("/searchhh")
public List<Profile> findProfiles(@RequestBody List<SearchCriteria> input) {
            System.out.println("criterias=" + input);
    
    return null;
}

Upvotes: 1

Donato Amasa
Donato Amasa

Reputation: 856

Have you tried this payload:

{
    "criterias" : [
        {
            "key": "g",
            "operation": "eq",
            "value": "m"
        },
        {
            "key": "name",
            "operation": "like",
            "value": "Rani"
        },
        {
            "key": "sh",
            "operation": "eq",
            "value": "Never"
        }
    ]
}

Upvotes: 2

Related Questions