簡體   English   中英

如何將 controller 中的 RequestBody 定義為列表,我收到 500 錯誤

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

我想將搜索輸入作為列表傳遞,請參考我嘗試過的以下代碼和有效負載,我收到解析器錯誤。

// 搜索輸入代碼

public class SearchInput {
    private List<SearchCriteria> criterias;

}

// 搜索條件中的代碼

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

//controller的代碼

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

// 我累了的有效載荷

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"
}

您是否嘗試過此有效負載:

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

您作為請求正文傳遞的上述有效負載表示SearchCriteria對象數組,因此您可以將 json 直接解析為List<SearchCriteria>而不需要SearchInput class

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM