- 重新实现utils.Struct2FlatMap

This commit is contained in:
gazebo
2019-09-24 15:23:27 +08:00
parent 3ae979e48b
commit b02230ec2d
3 changed files with 42 additions and 37 deletions

View File

@@ -13,7 +13,7 @@ import (
"time"
"git.rosy.net.cn/baseapi"
"github.com/fatih/structs"
"github.com/gazeboxu/structs"
"github.com/mitchellh/mapstructure"
)
@@ -449,43 +449,22 @@ func MergeMaps(firstMap map[string]interface{}, otherMaps ...map[string]interfac
return retVal
}
func Struct2Map(obj interface{}, tagName string) (mapData map[string]interface{}) {
func Struct2Map(obj interface{}, tagName string, isFlattenAnonymous bool) (mapData map[string]interface{}) {
if tagName == "" {
tagName = "json"
}
structsObj := structs.New(obj)
structsObj.TagName = tagName
structsObj.IsFlattenAnonymous = true
return structsObj.Map()
}
func Struct2MapByJson(obj interface{}) (mapData map[string]interface{}) {
return Struct2Map(obj, "")
}
// 此函数将MAP中所有的子MAP中的数据提升到最上层相同字段会覆盖父MAP的
func FlatMap(in map[string]interface{}) map[string]interface{} {
keys := []string{}
maps := []map[string]interface{}{}
for k, v := range in {
if vMap, ok := v.(map[string]interface{}); ok {
vMap = FlatMap(vMap)
maps = append(maps, vMap)
keys = append(keys, k)
}
}
if len(maps) > 0 {
retVal := MergeMaps(in, maps...)
for _, v := range keys {
delete(retVal, v)
}
return retVal
}
return in
return Struct2Map(obj, "", false)
}
func Struct2FlatMap(obj interface{}) map[string]interface{} {
m := Struct2MapByJson(obj)
return FlatMap(m)
return Struct2Map(obj, "", true)
}
// !!! 此函数好像不支持struct是内嵌结构的

View File

@@ -84,3 +84,40 @@ func TestTime(t *testing.T) {
}
}
}
func TestStruct2MapByJson(t *testing.T) {
type InnerKK struct {
IntData int
StrData string
ObjData time.Time
}
type KK struct {
IntData int
A int
B string
C time.Time
InnerKK
InnerKK2 InnerKK
}
kk := &KK{
InnerKK: InnerKK{
IntData: 1,
StrData: "hello",
},
}
mapData := Struct2MapByJson(kk)
t.Log(Format4Output(mapData, false))
// t.Log(mapData)
// t.Log(kk)
}
// func TestStruct2MapByJson(t *testing.T) {
// mapData := Struct2MapByJson(&struct {
// IntData int `structs:"dataInt"`
// StrData string `json:"-"`
// }{
// IntData: 1,
// StrData: "2",
// })
// t.Log(mapData)
// }

View File

@@ -175,17 +175,6 @@ func TestTrimBlanChar(t *testing.T) {
}
}
func TestStruct2MapByJson(t *testing.T) {
mapData := Struct2MapByJson(&struct {
IntData int `structs:"dataInt"`
StrData string `json:"-"`
}{
IntData: 1,
StrData: "2",
})
t.Log(mapData)
}
func TestLimitUTF8StringLen(t *testing.T) {
for _, v := range [][]interface{}{
[]interface{}{