omitempty custom json Marshaller

884 views
Skip to first unread message

Forud A

unread,
Dec 25, 2016, 8:36:47 AM12/25/16
to golang-nuts
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

C Banning

unread,
Dec 26, 2016, 8:20:17 AM12/26/16
to golang-nuts
Reply all
Reply to author
Forward
0 new messages