@RequestBody无法将JSON映射到Java对象-Spring Boot

时间:2019-06-28 17:07:40

标签: java json spring-boot mapping spring-restcontroller

我无法使用控制器类中的@RequestBody将JSON从帖子的方法主体转换为POJO。

我调试了错误,发现某些字段已映射而其他字段未映射。像这样的(POJO)

name: null, typeOfPlan: null, Email: example@gmail.com, PhoneNum: 123456789, Website: test.org, Username: null, password: 1234,这很奇怪。

JSON:

{
    "confirmPassword": "1234",
    "email": "example@gmail.com",
    "password": "1234",
    "phoneNum": "123456789",
    "name": "Hello world",
    "typeOfPlan": "Test",
    "userName": "user",
    "website": "test.org"
}

控制器

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

在这里,我调用服务,然后调用DAO类。

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

我还尝试过在consumes media type中允许使用带有@PostMapping的JSON,但未能解决该问题。

使用Jackson ObjectMapper效果不佳。

3 个答案:

答案 0 :(得分:1)

我的问题很简单::我在Angular项目中将数据发送到Spring Boot应用程序的变量拼写错误,因此后端应用程序无法识别,因此未映射到我的POJO正确。


更改前端表单变量以匹配POJO的变量后,我得到了:

POJO数据

name: It's good now, typeOfPlan: 2 Year, Email: example@gmail.com, PhoneNum: 123456789, Website: test.org, Username: Master, password: 1234

Spring Boot无法从JSON映射nametypeOfPlanUsername,因为它们根本与我的后端不匹配。


之前

Name, typeOfPlan, userName

之后

name, type, username

谢谢!

答案 1 :(得分:0)

首先,如果您使用的是Postman, curl etc..,请尝试通过以下方式发送json:

{
    "confirmPassword": "1234",
    "email": "example@gmail.com",
    "password": "1234",
    "phoneNum": "123456789",
    "name": "Hello world",
    "typeOfPlan": "Test",
    "userName": "user",
    "website": "test.org"
}

第二,我得到的唯一空值是username,因为您是通过以下方式在json中发送它的:userName,因此应检查json是否与{{1}兼容}

答案 2 :(得分:0)

我相信问题在于内容类型!将其设置为application/json。用邮递员或curl进行指定。

如果您使用js发送,请尝试以下示例

axios.post(
                "/rest/yoururl",
                jsObject
            ).then(
                function (response) {
                    console.log(response.data);
                }.bind(this)
            );

默认内容类型为json

通过卷曲:

curl --header "Content-Type: application/json" \
  --request POST \
  --data '{"username":"xyz","password":"xyz"}' \
  http://url

在邮递员中:

  

Headers->放置键Content-Type-> value application / json。如果你是   在邮递员中