@RequestBody not mapping JSON to Java Object - Spring Boot

Compiler v2 picture Compiler v2 · Jun 28, 2019 · Viewed 9.1k times · Source

I am unable to convert my JSON from post's method body into my POJO, with @RequestBody inside my controller class.

I debugged the error and I saw that certain fields were mapped and others were not. Like this (POJO):

name: null, typeOfPlan: null, Email: [email protected], PhoneNum: 123456789, Website: test.org, Username: null, password: 1234, which is strange.

JSON:

{
    "confirmPassword": "1234",
    "email": "[email protected]",
    "password": "1234",
    "phoneNum": "123456789",
    "name": "Hello world",
    "typeOfPlan": "Test",
    "userName": "user",
    "website": "test.org"
}

Controller

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class SomeController {

    @Autowired
    private Service foo;

    @CrossOrigin
    @PostMapping(value = "/create")
    private void createAccount(@RequestBody BigFoo bigFoo) {
        foo.createAccount(bigFoo);
    }
}

From here, I call my service, then DAO classes.

POJO

import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Getter;
import lombok.NoArgsConstructor;
import lombok.Setter;

@Getter
@Setter
@NoArgsConstructor
@JsonIgnoreProperties(ignoreUnknown = true)
public class BigFoo {

    private String name;
    private String typeOfPlan;
    private String email;
    private String website;
    private String phoneNum;
    private String username;
    private String password;
}

I have also tried to allow JSON with consumes media type in the @PostMapping, but it failed it solve this.

Using Jackson ObjectMapper did not work as well.

Answer

Compiler v2 picture Compiler v2 · Jun 29, 2019

My problem was simple: my variables in my Angular project, sending the data to my Spring Boot app were misspelled, and therefore were not recognized by my backend application and hence, were not mapped to my POJO correctly.


After I changed my frontend form variables to match my POJO's variables, I got this:

POJO data

name: It's good now, typeOfPlan: 2 Year, Email: [email protected], PhoneNum: 123456789, Website: test.org, Username: Master, password: 1234

Spring Boot was unable to map name, typeOfPlan & Username from the JSON because they simply did not match the ones in my backend.


Before

Name, typeOfPlan, userName

After

name, type, username

Thanks all!