Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Spring Boot Automatic JSON to Object at Controller

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

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?

like image 210
kamaci Avatar asked Oct 25 '16 18:10

kamaci


1 Answers

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;
}
like image 149
so-random-dude Avatar answered Oct 18 '22 05:10

so-random-dude