目录
一、问题复现:
上代码:
1、实体类
package com.example.demo;
/**
* @author Mr.xiong
* #description model
* #date: 2022/4/8 10:08
* @version v1.0.0
* @since jdk8
*/
public class model {
private String a;
private String b;
private boolean e;
private Boolean f;
public Boolean getF() {
return false;
}
public boolean isE() {
return false;
}
public boolean areC(){
return false;
}
public Boolean isD(){
return null;
}
public String getA() {
return a;
}
public void setA(String a) {
this.a = a;
}
public String getB() {
return b;
}
public void setB(String b) {
this.b = b;
}
}
2、controller类
package com.example.demo;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
import java.util.ArrayList;
import java.util.List;
/**
* @author Mr.xiong
* #description web
* #date: 2022/4/8 10:08
* @version v1.0.0
* @since jdk8
*/
@RestController
public class web {
@GetMapping
public R demo(){
model m1 = new model();
m1.setA("a1");
m1.setB("b1");
model m2 = new model();
m2.setA("a2");
m2.setB("b2");
List<model> models = new ArrayList<>();
models.add(m1);
models.add(m2);
return R.success(200,"success",models);
}
}
3、统一返回风格消息类
package com.example.demo;
import java.util.Objects;
/**
* @author Mr.xiong
* #description R
* #date: 2022/4/8 10:08
* @version v1.0.0
* @since jdk8
*/
public class R {
private Integer code;
private String msg;
private Object obj;
public R(Integer code, String msg) {
this.code = code;
this.msg = msg;
}
public R(Integer code, String msg, Object obj) {
this.code = code;
this.msg = msg;
this.obj = obj;
}
public Integer getCode() {
return code;
}
public void setCode(Integer code) {
this.code = code;
}
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public Object getObj() {
return obj;
}
public void setObj(Object obj) {
this.obj = obj;
}
@Override
public String toString() {
return "R{" +
"code=" + code +
", msg='" + msg + '\'' +
", obj=" + obj +
'}';
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
R r = (R) o;
return code.equals(r.code) && msg.equals(r.msg) && obj.equals(r.obj);
}
@Override
public int hashCode() {
return Objects.hash(code, msg, obj);
}
public static R success(Integer code,String msg){
return new R(code, msg);
}
public static R success(Integer code,String msg,Object obj){
return new R(code, msg,obj);
}
}
访问接口获得的数据如下:
二、问题分析及解决办法:
public Boolean isD(){ return null; } 可以看到,我们有这个方法,但是没有D这个属性,但是却实实在在打印了这个值。原因是因为springboot自动转json把他当做了一个属性。这是为什么呢?是因为布尔值的getter事实上boolean的getter方法就是 isXxxx,因此出现此问题也就不奇怪了解决方法,不要使用isXxx就可以避免此类问题。当我把isD修改为D之后,就解决了。如下: