Spring Boot Automatic JSON to Object at Controller

后端 未结 2 1356
深忆病人
深忆病人 2021-02-08 08:40

I have SpringBoot application with that dependencies:

    
        org.springframework.boot
        

        
2条回答
  •  傲寒
    傲寒 (楼主)
    2021-02-08 08:58

    SpringBoot by default comes with this functionality. You just have to use @RequestBody annotation in parameter declaration of your controller method but in contrast to @so-random-dude's answer you don't have to annotate fields with @JsonProperty, that is not required.

    You just have to provide getters and setters for your custom XML object class. I am posting an example below for simplicity.

    Example:

    Controller method declaration:-

    @PostMapping("/create")
        public ResponseEntity createNewPost(@RequestBody CreatePostRequestDto createPostRequest){
            //do stuff
            return response;
        }
    

    Your custom XML object class:-

    public class CreatePostRequestDto {
        String postPath;
    
        String postTitle;
    
        public String getPostPath() {
            return postPath;
        }
    
        public void setPostPath(String postPath) {
            this.postPath = postPath;
        }
    
        public String getPostTitle() {
            return postTitle;
        }
    
        public void setPostTitle(String postTitle) {
            this.postTitle = postTitle;
        }
    }
    

提交回复
热议问题