https://play.golang.org/p/WoCO7VGvDE
On Sunday, December 25, 2016 at 6:36:47 AM UTC-7, Forud A wrote: > > Hi, > I have a struct with custom json.MarshallJSON function. I need to ignore > field of this type when the value is null. something like this > > 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)) > > } > > > NOTE : this code has a runtime error > > if the FinalJSON.T1 = nil then the result is omited from the output, but I > want to handle it in MarshalJSON function. is there any way to handle this? > I get the structure from database, and I have a type like pq.NullTime with > extra MarshalJSON function, when the time is not Valid (.Valid == false), I > need to remove it from the json output. > > thank you > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. For more options, visit https://groups.google.com/d/optout.