当前位置:网站首页>golang 获取循环嵌套结构的tag
golang 获取循环嵌套结构的tag
2022-07-28 02:58:00 【用户昵称不能为空】
golang 获取
type Parent struct {
Age int `json:"age"`
City string `json:"city" cond:"title:城市"`
Name string `json:"name" cond:"title:name1"`
}
type Son struct {
Parent
Name string `json:"name" cond:"title:名字"`
}
需要对Son{} 进行获取循环嵌套的cond的结构的数据结果。
- 没有 cond 的忽略
- 继承的依旧优先级低
方法实现
package main
import (
"errors"
"fmt"
"reflect"
)
func GetAllTags(rt reflect.Type, key string) (tags map[string]reflect.StructField, err error) {
tags = make(map[string]reflect.StructField)
if rt.Kind() != reflect.Struct {
err = errors.New(fmt.Sprintf("bad type not struct %s", rt.Kind()))
return
}
for i := 0; i < rt.NumField(); i++ {
f := rt.Field(i)
// 嵌套型
if f.Type.Kind() == reflect.Struct {
var newTags map[string]reflect.StructField
newTags, err = GetAllTags(f.Type, key)
if err != nil {
return
}
for k, v := range newTags {
tags[k] = v
}
}
tag := f.Tag.Get(key)
if tag == "" {
continue
}
jsonName := f.Tag.Get("json")
if jsonName == "" {
err = errors.New(fmt.Sprintf("error %s missing tag JSON", f.Name))
return
}
tags[jsonName] = f
}
return
}
type Parent struct {
Age int `json:"age"`
City string `json:"city" cond:"title:城市"`
Name string `json:"name" cond:"title:name1"`
}
type Son struct {
Parent
Name string `json:"name" cond:"title:名字"`
}
func main() {
var (
err error
key = "cond"
alls map[string]reflect.StructField
)
{
alls, err = GetAllTags(reflect.TypeOf(Son{
}), key)
if err != nil {
fmt.Println("err1 = ", err.Error())
} else {
fmt.Println("alls = ", alls)
}
}
}
// outputs:
// alls = map[city:{City string json:"city" cond:"title:城市" 8 [1] false} name:{Name string json:"name" cond:"title:名字" 40 [1] false}]
边栏推荐
- 20条心灵鸡汤唯美句子,句句温情暖心!
- SQL Server备份数据库的方法
- bp svm的缺陷检测 树叶缺陷 叶片缺陷检测的系统设计
- Talk about the speech synthesis function of Baidu University of science and technology news Feiyun Zhisheng
- Redis persistence mechanism
- 力扣(LeetCode)208. 实现 Trie (前缀树)(2022.07.27)
- Scheme sharing | experts gather to jointly explore accent AI speech recognition
- xctf攻防世界 Web高手进阶区 unserialize3
- ELS displays a random square
- QT topic 1: implementing a simple calculator
猜你喜欢
随机推荐
[2022 Niuke multi school 2 K link with bracket sequence I] bracket linear DP
vba批量读取sql的create文来创建表
Comprehensive case
ThreadLocal usage scenario
QT official example: Fridge Magnets example
Comprehensive comparative study of image denoising
redis网络模型解析
Stm32f407 ------- DSP learning
关于湖北文理学院平衡信标组的疑问回应
ELS keyboard information
蓝桥杯:第九届—“彩灯控制器”
53. Maximum Subarray最大子数组和
Redis持久化机制
【2022 牛客第二场J题 Link with Arithmetic Progression】三分套三分/三分极值/线性方程拟合最小二乘法
Redis memory recycling
力扣(LeetCode)208. 实现 Trie (前缀树)(2022.07.27)
上位机与MES对接的几种方式
Talk about the speech synthesis function of Baidu University of science and technology news Feiyun Zhisheng
xctf攻防世界 Web高手进阶区 PHP2
More than 50 interviews have been summarized, and notes and detailed explanations have been taken from April to June (including core test sites and 6 large factories)









