Spring Boot Automatic JSON to Object at Controller

后端 未结 2 1354
深忆病人
深忆病人 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<ApplicationResponse> 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;
        }
    }
    
    0 讨论(0)
  • 2021-02-08 09:06

    Spring boot comes with Jackson out-of-the-box which will take care of un-marshaling JSON request body to Java objects

    You can use @RequestBody Spring MVC annotation to deserialize/un-marshall JSON string to Java object... For example.

    Example

    @RestController
    public class CustomerController {
        //@Autowired CustomerService customerService;
    
        @RequestMapping(path="/customers", method= RequestMethod.POST)
        @ResponseStatus(HttpStatus.CREATED)
        public Customer postCustomer(@RequestBody Customer customer){
            //return customerService.createCustomer(customer);
        }
    }
    

    Annotate your entities member elements with @JsonProperty with corresponding json field names.

    public class Customer {
        @JsonProperty("customer_id")
        private long customerId;
        @JsonProperty("first_name")
        private String firstName;
        @JsonProperty("last_name")
        private String lastName;
        @JsonProperty("town")
        private String town;
    }
    
    0 讨论(0)
提交回复
热议问题