如果它們中的任何一個為空,我試圖使Errorand Successstruct 消失package mainimport ( "encoding/json" "net/http")type appReturn struct { Suc *Success `json:"success,omitempty"` Err *Error `json:"error,omitempty"`}type Error struct { Code int `json:"code,omitempty"` Message string `json:"message,omitempty"`}type Success struct { Code int `json:"code,omitempty"` Message string `json:"message,omitempty"`}func init() { http.HandleFunc("/", handler)}func handler(w http.ResponseWriter, r *http.Request) { j := appReturn{&Success{}, &Error{}} js, _ := json.Marshal(&j) w.Header().Set("Content-Type", "application/json") w.Write(js)}輸出:{ success: { }, error: { }}如何從 JSON 輸出中隱藏ErrororSuccess結構?我認為將指針作為參數發送可以解決問題。
2 回答

忽然笑
TA貢獻1806條經驗 獲得超5個贊
這是因為appReturn.Suc
和appReturn.Err
不是空的;它們包含指向初始化結構的指針,而這些指針恰好在里面有 nil 指針。唯一的空指針是一個 nil 指針。
將 appReturn 初始化為 j := appReturn{}
- 2 回答
- 0 關注
- 334 瀏覽
添加回答
舉報
0/150
提交
取消