[英]I want to send a List(which is a member of an object) from Postman to Spring REST API
我有一個 object,它的屬性是一個列表。 我想將此 object 從 Postman 發送給我的服務。 I'm using Spring 5.2.7 (Spring MVC, not SpringBoot) and Hibernate 5.4.17 and Java 8. My problem is very similar to this one: I want to send a Postman POST request with an Array: members: ["william ", "埃里克", "瑞恩"]
這是我試圖傳入 Postman 的 class (POST 方法):
public class ChatDescriptionDto {
private String chatID;
private List<String> members;
private String chatType;
public String getChatID() {
return chatID;
}
public void setChatID(String chatID) {
this.chatID = chatID;
}
public List<String> getMembers() {
return members;
}
public void setMembers(List<String> members) {
this.members = members;
}
public void addMembers(List<String> members)
{
if(this.members == null)
this.members = new ArrayList<>();
this.members.addAll(members);
}
public void addMember(String member)
{
if(this.members == null)
this.members = new ArrayList<>();
this.members.add(member);
}
public String getChatType() {
return chatType;
}
public void setChatType(String chatType) {
this.chatType = chatType;
}
}
我已經嘗試過了,但它沒有用:
{
"chatID": "123",
"members": ["P2001222833","P2001640916"],
"chatType": "personal"
}
編輯:這是我的 controller:
@PostMapping("/initiateChat")
public String initiateChat(@RequestBody ChatDescriptionDto chat)
{
return chatServiceLocal.initiateChat(chat)?"Chat Description created":"Failure! Could not save.";
}
編輯2:我在問題中寫的方法"members": ["P2001222833","P2001640916"],
是正確的。 事實證明,服務器中有一些錯誤,所以它永遠不會啟動,我沒有檢查。
Having no information about the Controller
class you're using, the first thing I'd assume is that you're receiving an empty object, which means that Spring simply skipped the serialization. 當您沒有將方法的參數指定為@RequestBody
時,就會出現這種情況。 首先,確保您確實有注釋。
@RestController
@RequestMapping("/")
public class TestController {
@RequestMapping(value = "/test", method = RequestMethod.POST)
public ResponseEntity test(@RequestBody ChatDescriptionDto dto) {
System.out.println(dto);
return ResponseEntity.ok().build();
}
}
如果不是這種情況,我認為問題出在您使用的內容類型上。 Spring 默認使用 JSON,但您可以在端點配置中更改它。
要發送一個簡單的 object 請求,您可以:
{
“成員”:“可樂”
}
要發送列表 object 請求,您可以:
{
"成員": ["kola","wale","ojo"]
}
這更像是列出數組元素。
在這之后出現的任何錯誤,基本上都不是因為你發送的請求。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.