diff --git a/filter/impl/generic_filter.go b/filter/impl/generic_filter.go index 7fae41af39fd5991f8656310d300148debc0ec90..1ec4b99b823b8e514712b5ab3587c37513be24c0 100644 --- a/filter/impl/generic_filter.go +++ b/filter/impl/generic_filter.go @@ -75,19 +75,20 @@ func GetGenericFilter() filter.Filter { return &GenericFilter{} } func struct2MapAll(obj interface{}) interface{} { - result := make(map[string]interface{}) if obj == nil { return obj } t := reflect.TypeOf(obj) v := reflect.ValueOf(obj) - if t.Kind() == reflect.Struct { + result := make(map[string]interface{}) for i := 0; i < t.NumField(); i++ { if v.Field(i).Kind() == reflect.Struct { if v.Field(i).CanInterface() { result[headerAtoa(t.Field(i).Name)] = struct2MapAll(v.Field(i).Interface()) } + } else if v.Field(i).Kind() == reflect.Slice { + result[headerAtoa(t.Field(i).Name)] = struct2MapAll(v.Field(i).Interface()) } else { if v.Field(i).CanInterface() { if tagName := t.Field(i).Tag.Get("m"); tagName == "" { @@ -99,6 +100,14 @@ func struct2MapAll(obj interface{}) interface{} { } } return result + } else if t.Kind() == reflect.Slice { + value := reflect.ValueOf(obj) + var newTemps []interface{} + for i := 0; i < value.Len(); i++ { + newTemp := struct2MapAll(value.Index(i).Interface()) + newTemps = append(newTemps, newTemp) + } + return newTemps } else { return obj } diff --git a/filter/impl/generic_filter_test.go b/filter/impl/generic_filter_test.go index c9443449e7329d7357c068443f8997e150c72e9b..a71a9db95759a143186fe9a1a4fb0c861c8949e8 100644 --- a/filter/impl/generic_filter_test.go +++ b/filter/impl/generic_filter_test.go @@ -53,3 +53,37 @@ func Test_struct2MapAll(t *testing.T) { assert.Equal(t, reflect.Map, reflect.TypeOf(m["caCa"]).Kind()) assert.Equal(t, reflect.Map, reflect.TypeOf(m["caCa"].(map[string]interface{})["xxYy"]).Kind()) } + +type testStruct struct { + AaAa string + BaBa string `m:"baBa"` + XxYy struct { + xxXx string `m:"xxXx"` + Xx string `m:"xx"` + } `m:"xxYy"` +} + +func Test_struct2MapAll_Slice(t *testing.T) { + var testData struct { + AaAa string `m:"aaAa"` + BaBa string + CaCa []testStruct `m:"caCa"` + } + testData.AaAa = "1" + testData.BaBa = "1" + var tmp testStruct + tmp.BaBa = "2" + tmp.AaAa = "2" + tmp.XxYy.xxXx = "3" + tmp.XxYy.Xx = "3" + testData.CaCa = append(testData.CaCa, tmp) + m := struct2MapAll(testData).(map[string]interface{}) + + assert.Equal(t, "1", m["aaAa"].(string)) + assert.Equal(t, "1", m["baBa"].(string)) + assert.Equal(t, "2", m["caCa"].([]interface{})[0].(map[string]interface{})["aaAa"].(string)) + assert.Equal(t, "3", m["caCa"].([]interface{})[0].(map[string]interface{})["xxYy"].(map[string]interface{})["xx"].(string)) + + assert.Equal(t, reflect.Slice, reflect.TypeOf(m["caCa"]).Kind()) + assert.Equal(t, reflect.Map, reflect.TypeOf(m["caCa"].([]interface{})[0].(map[string]interface{})["xxYy"]).Kind()) +}