structs: fix custom tag names for nested structs

This commit is contained in:
Fatih Arslan 2015-05-06 17:41:32 +03:00
parent c06d8730d4
commit bc6c9948c8
2 changed files with 25 additions and 5 deletions

View File

@ -92,7 +92,9 @@ func (s *Struct) Map() map[string]interface{} {
if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") { if IsStruct(val.Interface()) && !tagOpts.Has("omitnested") {
// look out for embedded structs, and convert them to a // look out for embedded structs, and convert them to a
// map[string]interface{} too // map[string]interface{} too
finalVal = Map(val.Interface()) n := New(val.Interface())
n.TagName = s.TagName
finalVal = n.Map()
} else { } else {
finalVal = val.Interface() finalVal = val.Interface()
} }

View File

@ -115,17 +115,21 @@ func TestMap_Tag(t *testing.T) {
func TestMap_CustomTag(t *testing.T) { func TestMap_CustomTag(t *testing.T) {
var T = struct { var T = struct {
A string `dd:"x"` A string `json:"x"`
B int `dd:"y"` B int `json:"y"`
C bool `dd:"z"` C bool `json:"z"`
D struct {
E string `json:"jkl"`
} `json:"nested"`
}{ }{
A: "a-value", A: "a-value",
B: 2, B: 2,
C: true, C: true,
} }
T.D.E = "e-value"
s := New(T) s := New(T)
s.TagName = "dd" s.TagName = "json"
a := s.Map() a := s.Map()
@ -144,6 +148,20 @@ func TestMap_CustomTag(t *testing.T) {
} }
} }
nested, ok := a["nested"].(map[string]interface{})
if !ok {
t.Fatalf("Map should contain the D field that is tagged as 'nested'")
}
e, ok := nested["jkl"].(string)
if !ok {
t.Fatalf("Map should contain the D.E field that is tagged as 'jkl'")
}
if e != "e-value" {
t.Errorf("D.E field should be equal to 'e-value', got: '%v'", e)
}
} }
func TestMap_MultipleCustomTag(t *testing.T) { func TestMap_MultipleCustomTag(t *testing.T) {