Spring Boot自动JSON到控制器对象 [英] Spring Boot Automatic JSON to Object at Controller

查看:409
本文介绍了Spring Boot自动JSON到控制器对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有带有依赖关系的SpringBoot应用程序:

I have SpringBoot application with that dependencies:

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

我在我的控制器上有一个方法如下:

I have a method at my controller as follows:

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

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

I send a JSON object from my HTML via AJAX with some fields of XRequest type object (it is a plain POJO without any annotations). However my JSON is not constructed into object at my controller method and its fields are null.

在控制器上自动反序列化我错过了什么?

What I miss for an automatic deserialisation at my controller?

推荐答案

Spring启动时带有开箱即用的杰克逊,它将负责将JSON请求体解组到Java对象

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

您可以使用@RequestBody Spring MVC注释将json字符串解组为Java对象...例如。

You can use @RequestBody Spring MVC annotation to un-marshall json string to Java object... For 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);
    }
}

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

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

这篇关于Spring Boot自动JSON到控制器对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆