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字符集的可視字符組成業務系統故障碼,這樣做的好處:

不管在沈編碼環境,這個業務故障代碼都能正常顯示。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM