package main
import (
"encoding/json"
"fmt"
)
type Custom struct {
Name string
Show bool
}
type FinalJSON struct {
T1 *Custom `json:"field,omitempty"`
T2 string `json:"field2,omitempty"`
}
func (c *Custom) MarshalJSON() ([]byte, error) {
if !c.Show {
return nil, nil
}
return json.Marshal(c.Name)
}
func main() {
t1 := &Custom{Name: "c1", Show: true}
t2 := &Custom{Name: "c2", Show: false}
f1 := FinalJSON{T1: t1, T2: "Sss"}
f2 := FinalJSON{T1: t2, T2: "Sss2"}
j, err := json.Marshal(f1)
if err != nil {
panic(err)
}
fmt.Println(string(j))
j, err = json.Marshal(f2)
if err != nil {
panic(err)
}
fmt.Println(string(j))
}