spring web(SpringBoot,SpringMVC)项目中返回自定义格式的JSON,不暴露不必要/不相关的字段

笔者的web项目中使用RESTFul规范和前台进行交互。

原始代码

返回的json数据格式如下:

对应的后台实体类及交互方法:

JsonResult.java

public class JsonResult {

    private int code;
    private String message;
    private String nextUrl;
    private Object data;


    public JsonResult(int code, String message) {
        this.code = code;
        this.message = message;
    }

    public JsonResult(int code, String message, Object data) {
        this.code = code;
        this.message = message;
        this.data = data;
    }

    public JsonResult(int code, String message, String nextUrl) {
        this.code = code;
        this.message = message;
        this.nextUrl = nextUrl;
    }

    public int getCode() {
        return code;
    }

    public void setCode(int code) {
        this.code = code;
    }

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public String getNextUrl() {
        return nextUrl;
    }

    public void setNextUrl(String nextUrl) {
        this.nextUrl = nextUrl;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
}

controller代码:

@PostMapping(value = "offline")
@ResponseBody
public JsonResult offline() {
    if(xxxxx)
    return errorResult("appid无效");
    
    if(yyy){
    
     ImmutableMap<String, Object> result = ImmutableMap.of("uuid", conversionId, "code", 200);           
     return successResult("转换成功", result);
     }
}


protected JsonResult successResult(String message, String nextUrl) {
    return new JsonResult(200, message, nextUrl);
}

protected JsonResult successResult(String message, Object data) {
    return new JsonResult(200, message, data);
}
protected JsonResult errorResult(String message) {
    return new JsonResult(300, message);
}

以上返回的json格式在web交互的时候已经很精简了,而且封装的很不错

笔者最近需要对特定的web接口进行封装,封装成计费的API,这个时候上面格式里面的json节点显得多余

"data":
{
    "code":200,
    "uuid":"xxxxx"
}

于是笔者想到了Spring里面的ResponseEntity类

重构代码

@PostMapping(value = "offline")
@ResponseBody
public ResponseEntity<Map<String,Object>> offline(){

    if(StringUtils.isEmpty(apiKey)||StringUtils.isEmpty(apiKey))
    {
        return ResponseEntity.status(HttpStatus.BAD_REQUEST).body(ImmutableMap.of("message","apiKey和appId不能为空","code",300));
    }
        
    return ResponseEntity.ok().body(ImmutableMap.of("message","转换成功","code",200,"uuid",conversionId));
}

代码简洁了很多,返回的json如下

 其他方法

使用Jackson的@JsonIgnore,输出到客户端时将屏蔽这个字段

import com.fasterxml.jackson.annotation.JsonIgnore;
import com.google.common.base.Objects;
import com.google.gson.annotations.SerializedName;
import lombok.AllArgsConstructor;
import lombok.Builder;
import lombok.Data;
import lombok.NoArgsConstructor;

import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;

@Data
@NoArgsConstructor
@AllArgsConstructor
@Builder
@Table(name = "data_bytedance")
public class ByteDanceData {
    @Id
    @GeneratedValue(generator = "JDBC")
    @JsonIgnore
    private Integer id;

    private Integer distId;

    @SerializedName("confirm")
    private Integer confirm;
    @JsonIgnore
    @SerializedName("suspect")
    private Integer suspect;
    @SerializedName("dead")
    private Integer dead;

    @SerializedName("heal")
    private Integer heal;

    private float weight;

    @JsonIgnore
    @Transient
    private String level;

    private String updateTime;


    @Override
    public boolean equals(Object o) {
        if (this == o) {
            return true;
        }
        if (o == null || getClass() != o.getClass()) {
            return false;
        }
        ByteDanceData data = (ByteDanceData) o;
        return Objects.equal(distId, data.distId) &&
                Objects.equal(confirm, data.confirm) &&
                ("area".equals(level)?
                        Objects.equal(suspect, data.suspect):
                        true) &&
                Objects.equal(dead, data.dead) &&
                Objects.equal(heal, data.heal);
    }

    @Override
    public int hashCode() {
        return 0;
    }
}

建议

不建议将http状态码作为业务系统代码,比如上面的200,300,很容易让新手产生疑问,把排除问题故障的思路带偏了。当然按笔者的理解,设计上面JsonResult类的作者应该是出于

对简单业务的类型比较简单的交互设计了200,300两个状态,一般业务系统都会有自己的业务状态码,比如银行。而且多用ASCII字符集的可视字符组成业务系统故障码,这样做的好处:

不管在沈编码环境,这个业务故障代码都能正常显示。

原文地址:https://www.cnblogs.com/passedbylove/p/12299146.html