踩坑!Spring Boot 中@RequestBody 接收到的对象属性为null

定义的实体类

 

package com.fd.pojo;

import com.fasterxml.jackson.annotation.JsonProperty;

public class Alarm {
    private int id;
    private int AlarmTime;
    private int MsgFrom;
    private String MsgContent;
    private int MsgType;
    private int isSend;
    private String def1;

    public Alarm(int id, int alarmTime, int msgFrom, String msgContent, int msgType, int isSend, String def1) {
        this.id = id;
        AlarmTime = alarmTime;
        MsgFrom = msgFrom;
        MsgContent = msgContent;
        MsgType = msgType;
        this.isSend = isSend;
        this.def1 = def1;
    }
    public Alarm() {

    }
    @Override
    public String toString() {
        return "Alarm{" +
                "id=" + id +
                ", AlarmTime=" + AlarmTime +
                ", MsgFrom=" + MsgFrom +
                ", MsgContent='" + MsgContent + '\'' +
                ", MsgType=" + MsgType +
                ", isSend=" + isSend +
                ", def1='" + def1 + '\'' +
                '}';
    }

    public void setId(int id) {
        this.id = id;
    }

    public void setAlarmTime(int alarmTime) {
        AlarmTime = alarmTime;
    }

    public void setMsgFrom(int msgFrom) {
        MsgFrom = msgFrom;
    }
 
    public void setMsgContent(String msgContent) {
        MsgContent = msgContent;
    }

    public void setMsgType(int msgType) {
        MsgType = msgType;
    }

    public void setIsSend(int isSend) {
        this.isSend = isSend;
    }

    public void setDef1(String def1) {
        this.def1 = def1;
    }

    public int getId() {
        return id;
    }

    public int getAlarmTime() {
        return AlarmTime;
    }

    public int getMsgFrom() {
        return MsgFrom;
    }

    public String getMsgContent() {
        return MsgContent;
    }

    public int getMsgType() {
        return MsgType;
    }

    public int getIsSend() {
        return isSend;
    }

    public String getDef1() {
        return def1;
    }
}

 

controller类

package com.fd.controller;

import com.fd.pojo.Alarm;
import com.fd.pojo.User;
import com.fd.service.AlarmService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping(value = "/api")
public class AlarmController {

 


    @RequestMapping(value = "/into", method = RequestMethod.POST)
    public void addMsga(@RequestBody Alarm alarm) {
        System.out.println(alarm);
 
    }

}

 

 

发现问题:@RequestBody 接收到的对象属性为null

 

查阅资料,原因为:

spring mvc 默认使用jackson 对json进行解析,猜测是不是实体类的字段名在转换成json的时候字段属性名改变了。

springboot解析器在解析json过程中出现问题,因字段名驼峰命名无法匹配字段名导致,在实体类字段的set方法加上如下注解即可

@JsonProperty(value = "msgcontent")
    public void setMsgContent(String msgContent) {
        MsgContent = msgContent;
    }

 

在java中使用该变量,仍用原来变量名,json提交时,使用注解内的名字

你可能感兴趣的:(SpringBoot)