- 使用mapstructure进行map到struct的映射,简化API编写
This commit is contained in:
@@ -14,6 +14,7 @@ import (
|
||||
|
||||
"git.rosy.net.cn/baseapi"
|
||||
"github.com/fatih/structs"
|
||||
"github.com/mitchellh/mapstructure"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -471,58 +472,11 @@ func Struct2FlatMap(obj interface{}) map[string]interface{} {
|
||||
return FlatMap(m)
|
||||
}
|
||||
|
||||
func removeIgnoreFields(data interface{}, ignoreValues map[string]interface{}) {
|
||||
dataType := reflect.TypeOf(data).Kind()
|
||||
if dataType == reflect.Map {
|
||||
inMap := data.(map[string]interface{})
|
||||
for k, v := range inMap {
|
||||
// fmt.Printf("k:%s v:%v, ignoreValues[k]:%v\n", k, v, ignoreValues[k])
|
||||
if fmt.Sprint(ignoreValues[k]) == fmt.Sprint(v) {
|
||||
delete(inMap, k)
|
||||
} else {
|
||||
fieldType := reflect.TypeOf(v).Kind()
|
||||
if fieldType == reflect.Map || fieldType == reflect.Slice {
|
||||
removeIgnoreFields(v, ignoreValues)
|
||||
}
|
||||
}
|
||||
}
|
||||
} else if dataType == reflect.Slice {
|
||||
dataList := Interface2Slice(data)
|
||||
for _, v := range dataList {
|
||||
removeIgnoreFields(v, ignoreValues)
|
||||
}
|
||||
}
|
||||
// mapData := data.(map[string]interface{})
|
||||
// for k, v := range ignoreValues {
|
||||
// if fmt.Sprint(mapData[k]) == fmt.Sprint(v) {
|
||||
// delete(mapData, k)
|
||||
// }
|
||||
// }
|
||||
}
|
||||
|
||||
func Struct2MapWithIgnore(obj interface{}, ignoreValues map[string]interface{}) map[string]interface{} {
|
||||
mapData := Struct2FlatMap(obj)
|
||||
removeIgnoreFields(mapData, ignoreValues)
|
||||
return mapData
|
||||
}
|
||||
|
||||
// 注意:如下两个函数的行为与标准的json.Marshal的行为是有区别的
|
||||
// 这两个函数,只要成员是对象或map(不是指针),都会被展开
|
||||
// 而json.Marshal不是这样的,只会展开内嵌的(包括指针)
|
||||
// 所以原则是不用map的对象,行为就比较一致
|
||||
func MarshalJSONIgnoreValues(obj interface{}, ignoreValues map[string]interface{}) ([]byte, error) {
|
||||
return json.Marshal(Struct2MapWithIgnore(obj, ignoreValues))
|
||||
}
|
||||
|
||||
func MustMarshalJSONIgnoreValues(obj interface{}, ignoreValues map[string]interface{}) []byte {
|
||||
return MustMarshal(Struct2MapWithIgnore(obj, ignoreValues))
|
||||
}
|
||||
|
||||
func StructList2MapListWithIgnore(obj interface{}, ignoreValues map[string]interface{}) (mapList []map[string]interface{}) {
|
||||
objList := Interface2Slice(obj)
|
||||
mapList = make([]map[string]interface{}, len(objList))
|
||||
for k, v := range objList {
|
||||
mapList[k] = Struct2MapWithIgnore(v, ignoreValues)
|
||||
}
|
||||
return mapList
|
||||
func Map2StructByJson(inObj interface{}, outObjAddr interface{}, weaklyTypedInput bool) (err error) {
|
||||
decoder, _ := mapstructure.NewDecoder(&mapstructure.DecoderConfig{
|
||||
TagName: "json",
|
||||
Result: outObjAddr,
|
||||
WeaklyTypedInput: weaklyTypedInput,
|
||||
})
|
||||
return decoder.Decode(inObj)
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user