Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

Allow types to determine how to decode themselves #294

Open
wants to merge 2 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
11 changes: 11 additions & 0 deletions mapstructure.go
Expand Up @@ -453,6 +453,13 @@ func (d *Decoder) decode(name string, input interface{}, outVal reflect.Value) e
return nil
}

if outVal.CanAddr() {
v := outVal.Addr()
if u, ok := v.Interface().(decoder); ok {
return u.DecodeMapstructure(input)

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think it might make more sense to put this after the DecodeHook, so that any custom preprocessing can still happen.

}
}

if d.config.DecodeHook != nil {
// We have a DecodeHook, so let's pre-process the input.
var err error
Expand Down Expand Up @@ -1540,3 +1547,7 @@ func dereferencePtrToStructIfNeeded(v reflect.Value, tagName string) reflect.Val
}
return v
}

type decoder interface {
DecodeMapstructure(interface{}) error
}
29 changes: 29 additions & 0 deletions mapstructure_examples_test.go
Expand Up @@ -254,3 +254,32 @@ func ExampleDecode_omitempty() {
// Output:
// &map[Age:0 FirstName:Somebody]
}

type Someone struct {
Name string
}

func (p *Someone) DecodeMapstructure(v interface{}) error {
if name, ok := v.(string); ok {
p.Name = name
return nil
}
return fmt.Errorf("undecipherable name")
}

func ExampleDecode_custom_decoder_type() {
type Profile struct {
Friends []Someone
}
input := map[string]interface{}{
"friends": []string{"Mitchell"},
}
var result Profile
err := Decode(input, &result)
if err != nil {
panic(err)
}
fmt.Printf("%#v", result)
// Output:
// mapstructure.Profile{Friends:[]mapstructure.Someone{mapstructure.Someone{Name:"Mitchell"}}}
}