Created
May 12, 2021 07:20
-
-
Save itcuihao/25ffead8f77533ab3186903a4f2c3dc8 to your computer and use it in GitHub Desktop.
根据JSON的Tag给结构体赋值
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
func JsonAssignTo(n interface{}, tagName, value string) { | |
sv := reflect.ValueOf(n) | |
if sv.Kind() == reflect.Ptr { | |
//初始化空指针 | |
if sv.IsNil() && sv.CanSet() { | |
sv.Set(reflect.New(sv.Type().Elem())) | |
} | |
sv = sv.Elem() | |
} | |
// 发现tag | |
findJsonName := func(t reflect.StructTag, tag string) bool { | |
if jt, ok := t.Lookup("json"); ok { | |
return strings.Split(jt, ",")[0] == tag | |
} | |
return false | |
} | |
// 循环字段 | |
for i := 0; i < sv.NumField(); i++ { | |
fv := sv.Field(i) | |
if !fv.IsValid() || !fv.CanSet() { | |
continue | |
} | |
ft := sv.Type().Field(i) | |
find := findJsonName(ft.Tag, tagName) | |
if !find { | |
continue | |
} | |
// 根据结构体中的字段类型转换赋值 | |
switch sv.Field(i).Kind() { | |
case reflect.String: | |
fv.Set(reflect.ValueOf(value)) | |
case reflect.Int: | |
if strings.Contains(value, ".") { | |
vf, _ := strconv.ParseFloat(value, 64) | |
fv.Set(reflect.ValueOf(int(vf))) | |
} else { | |
vi, _ := strconv.Atoi(value) | |
fv.Set(reflect.ValueOf(vi)) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
方法接收 结构体指针,tag,value