Spring Boot Automatic JSON to Object at Controller

kamaci :

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?

so-random-dude :

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

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=454414&siteId=1