Standard library / encoding/json
encoding/json.Unmarshaler
Custom JSON decoding interface. Unmarshal calls UnmarshalJSON even for JSON null; implementations must define null handling and copy any retained input. Expected stdout: 'go\n'.
Formal Syntax & Structure
go syntaxgo
type Unmarshaler interface { UnmarshalJSON([]byte) error}Working Example
Example Snippetgo
package main
import ( "encoding/json" "fmt" "strings")
func must(e error) { if e != nil { panic(e) }}
type Label string
func (l *Label) UnmarshalJSON(b []byte) error { var s string if e := json.Unmarshal(b, &s); e != nil { return e } *l = Label(strings.ToLower(s)) return nil}func main() { var l Label var u json.Unmarshaler = &l must(json.Unmarshal([]byte(`"GO"`), u)) fmt.Println(l)}