Spring Boot自动JSON到控制器上的对象


问题内容

我有带有该依赖项的SpringBoot应用程序:

    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-jersey</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-security</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>

我在控制器上有一个方法,如下所示:

@RequestMapping(value = "/liamo", method = RequestMethod.POST)
@ResponseBody
public XResponse liamo(XRequest xRequest) {
    ...
    return something;
}

我通过AJAX从HTML发送一个JSON对象,并带有XRequest类型对象的某些字段(这是一个没有任何注释的普通POJO)。但是,我的JSON并未在控制器方法中构造为object,并且其字段为null。

我想在控制器上进行自动反序列化时会错过什么?


问题答案:

Spring Boot附带了现成的Jackson,它将负责将JSON请求主体解编为Java对象

您可以使用@RequestBody Spring MVC批注将JSON字符串反序列化/解编为Java对象…例如。

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

使用@JsonProperty和相应的json字段名称注释您的实体成员元素。

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