我想建立的程序,设置字段的结构使用反射。我让它为顶级字段工作,但我正在努力与嵌套结构字段。如何遍历嵌套的结构体字段?
type Payload struct {
Type string `json:"type"`
SubItem *SubItem `json:"sub_item"`
}
type SubItem struct {
Foo string `json:"foo"`
}
func main() {
var payload Payload
setValue(&payload, "type", "test1")
setValue(&payload, "sub_item.foo", "test2")
}
func setValue(structPtr interface{}, key string, value string) {
structValue := reflect.Indirect(reflect.ValueOf(structPtr))
for i, subkey := range strings.Split(key, ".") {
isLast := i == len(strings.Split(key, "."))-1
var found bool
// this line is crashing with "reflect: call of reflect.Value.NumField on zero Value"
for i := 0; i < structValue.NumField(); i++ {
field := structValue.Type().Field(i)
jsonTags := strings.Split(field.Tag.Get("json"), ",")
if jsonTags[0] == subkey {
found = true
if isLast {
if isLast {
// last element
// TODO set value
fmt.Printf("TODO set value %s to %v", value, structValue)
structValue = reflect.Indirect(reflect.ValueOf(structPtr))
}
} else {
structValue = reflect.Indirect(reflect.ValueOf(structValue.Field(i).Interface()))
}
break
}
}
if !found {
panic(fmt.Errorf("failed to find field %s", key))
}
}
}
1条答案
按热度按时间kx1ctssn1#
使用此功能:
函数findJSONField通过字段的JSON标记查找结构字段:
https://go.dev/play/p/DnSuydQgQt9