Spring Load automatic JSON into an object on the controller

I have a SpringBoot application with these 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 on my controller as follows:

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

I am sending a JSON object from my HTML via AJAX with some fields of an object of type XRequest (this is a simple POJO without any annotations). However, my JSON is not built in the object according to my controller method, and its fields are zero.

What did I skip for automatic deserialization on my controller?

+8
source share
2 answers

Spring boot comes with Jackson out of the box, which will take care of not marshaling the JSON request body for Java objects

@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;
}
+14

SpringBoot . @RequestBody , @so-random-dude @JsonProperty, .

XML. .

:

: -

@PostMapping("/create")
    public ResponseEntity<ApplicationResponse> createNewPost(@RequestBody CreatePostRequestDto createPostRequest){
        //do stuff
        return response;
    }

XML: -

public class CreatePostRequestDto {
    String postPath;

    String postTitle;

    public String getPostPath() {
        return postPath;
    }

    public void setPostPath(String postPath) {
        this.postPath = postPath;
    }

    public String getPostTitle() {
        return postTitle;
    }

    public void setPostTitle(String postTitle) {
        this.postTitle = postTitle;
    }
}
0

Source: https://habr.com/ru/post/1658855/


All Articles