Golang-从JSON响应中隐藏空结构
我试图使Golang-从JSON响应中隐藏空结构,json,google-app-engine,struct,go,Json,Google App Engine,Struct,Go,我试图使错误和成功结构在其中一个为空时消失 package main import ( "encoding/json" "net/http" ) type appReturn struct { Suc *Success `json:"success,omitempty"` Err *Error `json:"error,omitempty"` } type Error struct { Code int `json:"code,omi
错误
和成功
结构在其中一个为空时消失
package main
import (
"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输出中隐藏错误
或成功
结构?
我认为将指针作为参数发送就可以了。这是因为
appReturn.Suc
和appReturn.Err
不是空的;它们包含指向初始化结构的指针,而初始化结构中恰好有nil指针。唯一的空指针是nil指针
将appReturn初始化为
j:=appReturn{}
这是因为appReturn.Suc
和appReturn.Err
不为空;它们包含指向初始化结构的指针,而初始化结构中恰好有nil指针。唯一的空指针是nil指针
将appReturn初始化为
j:=appReturn{}
您可以为任一参数传入nil
,使其消失:
如果出于任何原因无法执行此操作,也可以编写自定义JSON封送拆收器来检查空结构:
您可以为任一参数传入
nil
,使其消失:
如果出于任何原因无法执行此操作,也可以编写自定义JSON封送拆收器来检查空结构:
j := appReturn{&Success{}, nil}
js, _ := json.Marshal(&j)
fmt.Println(string(js))
j = appReturn{nil, &Error{}}
js, _ = json.Marshal(&j)
fmt.Println(string(js))
j = appReturn{nil, nil}
js, _ = json.Marshal(&j)
fmt.Println(string(js))
func (j appReturn) MarshalJSON() ([]byte, error) {
suc, _ := json.Marshal(j.Suc)
err, _ := json.Marshal(j.Err)
if (string(err) == "{}") {
return []byte("{\"success\":" + string(suc) + "}"), nil
} else {
return []byte("{\"error\":" + string(err) + "}"), nil
}
}