Skip to content
Advertisement

I want to send a List(which is a member of an object) from Postman to Spring REST API

I have an object, and of its attributes is a List. I want to send this object from Postman to my service. 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”, “eric”, “ryan”]

This is the class I’m trying to pass in Postman (POST method):

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

I’ve tried this and it didn’t work:

{
    "chatID": "123",
    "members": ["P2001222833","P2001640916"],
    "chatType": "personal"
}

Edit: This is my controller:

@PostMapping("/initiateChat")
public String initiateChat(@RequestBody ChatDescriptionDto chat)
{
    return chatServiceLocal.initiateChat(chat)?"Chat Description created":"Failure! Could not save.";
}

Edit 2: The method which I’ve written in the question, "members": ["P2001222833","P2001640916"], is the correct one. Turns out, there was some error in the server so it never started and I didn’t check that.

Advertisement

Answer

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. This is the case when you don’t specify the parameter of the method as @RequestBody. First, make sure that you do have the annotation.

@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();
    }

}

If that’s not the case, I’d assume that the problem is with the content type you’re using. Spring uses JSON by default, but you can change it in your endpoint’s configuration.

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement