Skip to content

Instantly share code, notes, and snippets.

@itcuihao
Created May 12, 2021 07:20
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save itcuihao/25ffead8f77533ab3186903a4f2c3dc8 to your computer and use it in GitHub Desktop.
Save itcuihao/25ffead8f77533ab3186903a4f2c3dc8 to your computer and use it in GitHub Desktop.
根据JSON的Tag给结构体赋值
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))
}
}
}
}
@itcuihao
Copy link
Author

方法接收 结构体指针,tag,value

func TestNpcR(t *testing.T) {
	n := &NPCSheetRow{}
	JsonAssignTo(n, "type", "3")
	t.Logf("%+v\n", n)
	JsonAssignTo(n, "npc_id", "1")
	t.Logf("%+v\n", n)
	JsonAssignTo(n, "name_cn", "666hhh")
	t.Logf("%+v\n", n)
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment