Map转换
gconv.Map
支持将任意的map
或struct
/*struct
类型转换为常用的 map[string]interface{}
类型。当转换参数为struct
/*struct
类型时,支持自动识别struct
的 c/gconv/json
标签,并且可以通过Map
方法的第二个参数tags
指定自定义的转换标签,以及多个标签解析的优先级。如果转换失败,返回nil
。
...
更多的
map
相关转换方法请参考接口文档:https://godoc.org/github.com/gogf/gf/util/gconv
示例1,基本示例
package main
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/util/gconv"
)
func main() {
type User struct {
Uid int `c:"uid"`
Name string `c:"name"`
}
// 对象
g.Dump(gconv.Map(User{
Uid: 1,
Name: "john",
}))
// 对象指针
g.Dump(gconv.Map(&User{
Uid: 1,
Name: "john",
}))
// 任意map类型
g.Dump(gconv.Map(map[int]int{
100: 10000,
}))
}
...
{
"name": "john",
"uid": 1
}
{
"name": "john",
"uid": 1
}
{
"100": 10000
}
示例2,属性标签
package main
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/util/gconv"
)
func main() {
type User struct {
Uid int
Name string `c:"-"`
NickName string `c:"nickname, omitempty"`
Pass1 string `c:"password1"`
Pass2 string `c:"password2"`
}
user := User{
Uid: 100,
Name: "john",
Pass1: "123",
Pass2: "456",
}
g.Dump(gconv.Map(user))
}
...
{
"Uid": 100,
"password1": "123",
"password2": "456"
}
示例3,自定义标签
package main
import (
"github.com/gogf/gf/frame/g"
"github.com/gogf/gf/util/gconv"
)
func main() {
type User struct {
Id int `c:"uid"`
Name string `my-tag:"nick-name" c:"name"`
}
user := &User{
Id: 1,
Name: "john",
}
g.Dump(gconv.Map(user, "my-tag"))
}
...
{
"nick-name": "john",
"uid": 1
}
示例4,递归转换
当参数为map
/struct
/*struct
类型时,如果键值/属性为一个对象(或者对象指针)时,Map
方法将会将对象转换为结果的一个键值。我们可以使用MapDeep
方法递归转换参数的子对象。
...