I'm trying to make the Error
and Success
struct disappear if either one of them is empty
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)
}
Output:
{
success: { },
error: { }
}
How can I hide the Error
or Success
struct from the JSON output? I thought that sending the pointer as an argument would do the trick.
You can pass in nil
for either argument to make it disappear:
http://play.golang.org/p/9Say6mVzCg
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))
If for whatever reason you can't do that, you could also write a custom JSON marshaler to check for the empty struct:
http://play.golang.org/p/W0UhB4qtXH
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
}
}
This is because appReturn.Suc
and appReturn.Err
are not empty; they contain pointers to initialized structs, which just happen to have nil pointers inside. The only empty pointer is a nil pointer.
Initialize appReturn as j := appReturn{}