例:
const tagName = "validate"
type employee struct {
ID int `json:"id"`
Name string `json:"名字" validate:"presence,min=2,max=40"`
Age int `json:"年龄"`
Desc string `json:"描述" back:"好看否"`
weight float64 `json:"weight" 单位:"kg"`
Salary float64 `json:"-"`
Email string `validate:"email,required"`
MateName string `json:"mate_name,omitempty"`
}
转为json类型时
zhangsan := employee{
ID: 1,
Name: "张三",
Age: 18,
Desc: "秀色可餐",
weight: 48.0,
Salary: 12.0,
MateName:"Prince",
}
fmt.Println(zhangsan)
re,_:=json.Marshal(zhangsan)
fmt.Println(string(re))
t:=reflect.TypeOf(zhangsan)
fmt.Println("Type: ",t.Name())
fmt.Println("Kind: ",t.Kind())
fmt.Println(t.NumField())
说明:转换为json格式时,tag中
ID-id
Name-名字
Age- 年龄
weight 没有转换
josn加‘-’不转换Salary float64 `json:"-"` 不 转换
我的感觉是字段有值则不忽略,没有值则忽略
zhangsan := employee{
ID: 1,
Name: "张三",
Age: 18,
Desc: "秀色可餐",
weight: 48.0,
Salary: 12.0,
//MateName:"Prince",
}
结果:
{"id":1,"名字":"张三","年龄":18,"描述":"秀色可餐","Email":""}
反射机制
zhangsan := employee{
ID: 1,
Name: "张三",
Age: 18,
Desc: "秀色可餐",
weight: 48.0,
Salary: 12.0,
MateName:"Prince",
}
t:=reflect.TypeOf(zhangsan)
fmt.Println("Type: ",t.Name())
fmt.Println("Kind: ",t.Kind())
fmt.Println(t.NumField())
for i:=0;i<t.NumField();i++{
field:=t.Field(i)
tag:=field.Tag.Get(tagName)
fmt.Printf("%d. %v(%v), tag:'%v'\n", i+1, field.Name, field.Type.Name(), tag)
通过reflect包我们能够获取结构体的基本信息,包括它的类型、种类且能列出它的所有字段。field.Tag.Get方法返回与标签名匹配的字符串,你可以自由使用做你想做的。