Skip to content
Snippets Groups Projects
Commit 1faca0c8 authored by pantianying's avatar pantianying
Browse files

generic filter add slice support

parent 4271bcca
No related branches found
No related tags found
No related merge requests found
......@@ -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
}
......
......@@ -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())
}
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment