4 ms·
You can have whatever default value you like by initialising the struct before you pass it to json.Unmarshal. If the key isn't present, it won't be set: ty
by shabbyrobe 9y ago
You can have whatever default value you like by initialising the struct before you pass it to json.Unmarshal. If the key isn't present, it won't be set:
type Test struct {
Foo string
Bar string
}
func NewTest() *Test {
return &Test{Foo: "a"}
}
func main() {
t := NewTest()
if err := json.Unmarshal([]byte(`{"Bar": "b"}`), t); err != nil {
log.Fatal(err)
}
fmt.Printf("%#v\n", t)
}
Output:
&main.Test{Foo:"a", Bar:"b"}