UnmarshalJSON is a method convention that lets a Go type control how JSON bytes become a value. It is useful when ordinary field mapping must include validation or transformation, such as requiring Config.Host to contain a valid URL. section 10.5.1
Implement custom decoding by following this pattern:
- Define UnmarshalJSON on the receiving type. section 10.5.1
- Decode into a temporary anonymous struct with JSON tags, avoiding recursive calls to the method. section 10.5.1
- Validate or transform the temporary fields and return parsing errors immediately. section 10.5.1
- Assign the validated temporary value to the receiver. section 10.5.1
Validate a configuration host
func (c *Config) UnmarshalJSON(b []byte) error { temp := struct { Name string `json:"name"` Version string `json:"version"` Debug bool `json:"debug"` Port int `json:"port"` Host string `json:"host"` }{} if err := json.Unmarshal(b, &temp); err != nil { return err } if _, err := url.ParseRequestURI(temp.Host); err != nil { return fmt.Errorf("invalid Host URL: %v", err) } *c = Config(temp) return nil } section 10.5.1
Listing 10.16 config.json: Configuration defined in JSON format
{
"name": "myapp",
"version": "1.0.0",
"debug": false,
"port": 8080,
"host": "localhost"
}
Use the configuration JSON example to trace ordinary field decoding before adding custom Host validation. section 10.5.1
