Spring Boot Automatic JSON to Object at Controller

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

I have SpringBoot application with that dependencies:

    
        org.springframework.boot
        

        
2条回答
  •  轻奢々
    轻奢々 (楼主)
    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;
    }
    

提交回复
热议问题