wrapper/map.go

96 lines
2.2 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

// Package wrapper ...
//
// Description : wrapper ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2023-08-10 15:01
package wrapper
import (
"encoding/json"
"errors"
"git.zhangdeman.cn/zhangdeman/easymap"
"git.zhangdeman.cn/zhangdeman/serialize"
"github.com/tidwall/gjson"
"reflect"
)
// EasyMap ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:02 2023/8/10
func EasyMap(mapData any) Map {
m, _ := EasyMapWithError(mapData)
return m
}
// EasyMapWithError 转换map并带上转换的异常
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:06 2023/8/10
func EasyMapWithError(mapData any) (Map, error) {
if nil == mapData {
return easymap.NewNormal(), nil
}
m := easymap.NewNormal()
reflectType := reflect.TypeOf(mapData)
if reflectType.Kind() != reflect.Map {
mapFormatData := make(map[string]any)
if err := serialize.JSON.UnmarshalWithNumber(serialize.JSON.MarshalForByte(mapData), &mapFormatData); nil != err {
return m, errors.New("input data type is " + reflectType.String() + ", can not convert to map")
}
mapData = mapFormatData
}
reflectValue := reflect.ValueOf(mapData).MapRange()
for reflectValue.Next() {
// 循环提取相关值
m.Set(reflectValue.Key().Interface(), reflectValue.Value().Interface())
}
return m, nil
}
// EasyMapFromStruct 从struct转map
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:11 2023/8/10
func EasyMapFromStruct(data any) Map {
byteData, _ := json.Marshal(data)
return EasyMapFromByte(byteData)
}
// EasyMapFromString 从string转为Map
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:12 2023/8/10
func EasyMapFromString(data string) Map {
return EasyMapFromByte([]byte(data))
}
// EasyMapFromByte 从字节数组转为Map
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 16:12 2023/8/10
func EasyMapFromByte(data []byte) Map {
res := easymap.NewNormal()
jsonRes := gjson.Parse(string(data))
jsonRes.ForEach(func(key, value gjson.Result) bool {
res.Set(key.Value(), value.Value())
return true
})
return res
}
// Map ...
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 15:14 2023/8/10
type Map easymap.EasyMap