切片、map 转 struct
map to struct
package interfce_to_struct
import (
"errors"
"reflect"
"strings"
)
type Person struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
Sex int `json:"sex"`
}
func Map2Struct(m map[string]interface{}, u interface{}, tag string) error {
valueOf := reflect.ValueOf(u)
if valueOf.Kind() != reflect.Ptr {
return errors.New("must ptr")
}
valueOf = valueOf.Elem()
typeOf := valueOf.Type()
if valueOf.Kind() != reflect.Struct {
return errors.New("must struct")
}
for i := 0; i < valueOf.NumField(); i++ {
//获取字段类型/获取字段标签
var fieldName = typeOf.Field(i).Name
if tag != "" {
fieldName = strings.Split(typeOf.Field(i).Tag.Get(tag), ",")[0]
}
//var fieldName=valueOf.Type().Field(i).Name
if val, ok := m[fieldName]; ok {
if val != nil && reflect.ValueOf(val).Kind() == valueOf.Field(i).Kind() {
valueOf.Field(i).Set(reflect.ValueOf(val))
}
}
}
return nil
}
func main() {
// 反射 map to struct
var per = &interfce_to_struct.Person{}
var m = map[string]interface{}{
"name": "xj",
"Age": 12,
"Sex": 1,
}
_ = map_to_struct.Map2Struct(m, per, "json")
fmt.Printf("result:%+v\n", per)
fmt.Println("end.......")
}
切片转结构体
package interface_to_struct
import (
"errors"
"reflect"
)
type Person struct {
ID int `json:"id"`
Name string `json:"name"`
Age int `json:"age"`
Sex int `json:"sex"`
}
func Slice2Struct(arr []interface{}, u interface{}) error {
valueOf := reflect.ValueOf(u)
if valueOf.Kind() != reflect.Ptr {
return errors.New("must ptr")
}
valueOf = valueOf.Elem()
if valueOf.Kind() != reflect.Struct {
return errors.New("must struct")
}
for i := 0; i < valueOf.NumField(); i++ {
if i >= len(arr) {
break
}
val := arr[i]
if val != nil && reflect.ValueOf(val).Kind() == valueOf.Field(i).Kind() {
valueOf.Field(i).Set(reflect.ValueOf(val))
}
}
return nil
}
func main() {
// 反射 slice to struct
var per = &interface_to_struct.Person{}
var arr = []interface{}{1, "xj", 20, 1}
_ = interface_to_struct.Slice2Struct(arr, per)
fmt.Printf("result:%+v\n", per)
fmt.Println("end.......")
}