Spring Boot中解析属性首字母为大写的Json串的解决方案

  假设收到Post方法HTTP报文,其body部分内容如下:

{

"AuditState" : "pass",

"CurPage": "0",

"PageSize": 10,

"Status": "refuse"

}

为处理此请求,Controller定义如下:

@RequestMapping(value = "/PostToken", method = RequestMethod.POST)
public void getToken(@RequestBodyDealerCondition condition){
    DealerCondition dealerCondition = newDealerCondition();
    dealerCondition.setAuditState(condition.getAuditState());
    dealerCondition.setCurPage(condition.getCurPage());
    return;
}

 

用于接收Post报文中的json串的模型定义如下:

public class DealerCondition {
    private String AuditState ;
    private int CurPage;
    private int PageSize;

    public String getAuditState() {
        return AuditState;
    }
    public void setAuditState(String auditState) {
        AuditState = auditState;
    }
    public int getCurPage() {
        return CurPage;
    }
    public void setCurPage(intcurPage) {
        CurPage = curPage;
    }
    public int getPageSize() {
        return PageSize;
    }
    public void setPageSize(intpageSize) {
        PageSize = pageSize;
    }
}

 

虽然为了想成功解析参数,特意将DealerCondition中的属性首字母定义为大写,与json参数保持一致,但仍然无济于事,如下图所示,解析出的属性全部为null

 Spring Boot中解析属性首字母为大写的Json串的解决方案_第1张图片

 

查找相关资料后,找到两种解决方案:

方案一:将DealerCondition的属性首字母全部改为大写的同时,需要将访问级别改为public类型 (此种方案虽然能够解决问题,但有悖于面向对象的封装特性)

方案二:使用JsonProperty注解,如下形式

public class DealerCondition {
    @JsonProperty(value = "AuditState")
    private String AuditState ;
    @JsonProperty(value = "CurPage")
    private int CurPage;
    @JsonProperty(value = "PageSize")
    private int PageSize;

    public String getAuditState() {
        return AuditState;
    }
    public void setAuditState(String auditState) {
        AuditState = auditState;
    }
    public int getCurPage() {
        return CurPage;
    }
    public void setCurPage(intcurPage) {
        CurPage = curPage;
    }
    public int getPageSize() {
        return PageSize;
    }
    public void setPageSize(intpageSize) {
        PageSize = pageSize;
    }
}

 

你可能感兴趣的:(----------,【Java】,编程语言)