Implement custom JSON marshalers
Implement custom JSON marshalers
Implement MarshalJSON() ([]byte,error) to define a type’s JSON representation and UnmarshalJSON([]byte) error to parse it. A value receiver can encode a value; decoding typically needs a pointer receiver to update it. Use existing JSON functions for primitives rather than manually quoting strings.
package main
import ( "encoding/json" "errors" "fmt" "strconv")
func check(e error) { if e != nil { panic(e) }}
type Code int
func (c Code) MarshalJSON() ([]byte, error) { if c < 0 { return nil, errors.New("negative code") } return json.Marshal(strconv.Itoa(int(c)))}func (c *Code) UnmarshalJSON(b []byte) error { var s string if e := json.Unmarshal(b, &s); e != nil { return e } n, e := strconv.Atoi(s) if e != nil || n < 0 { return errors.New("invalid code") } *c = Code(n) return nil}func main() { b, e := json.Marshal(Code(7)) check(e) fmt.Println(string(b)) var c Code check(json.Unmarshal(b, &c)) fmt.Println(int(c))}The wire format is a JSON string containing a nonnegative integer within the Go int range. Parse into a temporary value and assign only on success. Passing c itself to json.Marshal inside its MarshalJSON method would recursively call the same method; converting to a primitive avoids that. Choose a fixed-width integer for cross-architecture range stability in a real protocol.
Expected output:
"7"7Reject invalid values without changing the receiver
package main
import ( "encoding/json" "errors" "fmt")
func check(e error) { if e != nil { panic(e) }}
type Count int
func (c *Count) UnmarshalJSON(b []byte) error { var n *int if e := json.Unmarshal(b, &n); e != nil { return e } if n == nil || *n < 0 { return errors.New("expected nonnegative integer") } *c = Count(*n) return nil}func main() { c := Count(4) e := json.Unmarshal([]byte(`-1`), &c) fmt.Println(e != nil, c)}Using a temporary pointer lets this type reject JSON null as well as negative integers. Do not mutate the receiver before validation; the previous value remains intact on this error path. A nil pointer passed directly to Marshal is encoded as null rather than invoking its method.
Expected output:
true 4Try it locally
Define a Flag bool type with MarshalJSON returning the JSON string "on" or "off". Marshal true.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Serialization 05: Implement custom JSON marshalers
Check the lesson objective before moving on.
Which receiver normally lets UnmarshalJSON update the original value?
What avoids recursive MarshalJSON dispatch?