Created
June 29, 2020 15:55
-
-
Save dwburke/ad02125c489a03b0fd03da1ec3dbe085 to your computer and use it in GitHub Desktop.
Default values when unmarshalling json in go
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package foo | |
type Foo struct { | |
Field string `json:"field"` | |
} | |
// UnmarshalJSON is the implementation of the json.Unmarshaler interface. | |
func (t *Foo) UnmarshalJSON(data []byte) error { | |
type innerFoo Foo | |
inner := &innerFoo{ | |
Field: "default value", | |
} | |
if err := json.Unmarshal(data, inner); err != nil { | |
return err | |
} | |
*t = Foo(*inner) | |
return nil | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
example to set default values on a struct when unmarshing json