问题

jsontagtag

举例

tag反射(reflect包)
package main

import (
    "fmt"
    "reflect"
)

type J struct {
    a string //小写无tag
    b string `json:"B"` //小写+tag
    C string //大写无tag
    D string `json:"DD" otherTag:"good"` //大写+tag
}

func printTag(stru interface{}) {
    t := reflect.TypeOf(stru).Elem()
    for i := 0; i < t.NumField(); i++ {
        fmt.Printf("结构体内第%v个字段 %v 对应的json tag是 %v , 还有otherTag? = %v \n", i+1, t.Field(i).Name, t.Field(i).Tag.Get("json"), t.Field(i).Tag.Get("otherTag"))
	}
}

func main() {
    j := J{
      a: "1",
      b: "2",
      C: "3",
      D: "4",
    }
    printTag(&j)
}

输出

结构体内第1个字段 a 对应的json tag是  , 还有otherTag? =  
结构体内第2个字段 b 对应的json tag是 B , 还有otherTag? =  
结构体内第3个字段 C 对应的json tag是  , 还有otherTag? =  
结构体内第4个字段 D 对应的json tag是 DD , 还有otherTag? = good 

解释

printTagreflect.TypeOf(stru).Elem()NumField()t.Field(i).Tag.Get("json")tagjson多个tagotherTagt.Field(i).Tag.Get("otherTag")

再补一句

json包私有变量的tag反射信息t.Field(i).Tag.Get("json")json字段
jsontagjsonUnexportedjsontag/src/encoding/json/encode.go:1070
func typeFields(t reflect.Type) []field {
    // 注释掉其他逻辑...
    // 遍历结构体内的每个字段
    for i := 0; i < f.typ.NumField(); i++ {
        sf := f.typ.Field(i)
        isUnexported := sf.PkgPath != ""
        // 注释掉其他逻辑...
        if isUnexported {
            // 如果是不可导出的变量则跳过
            continue
        }
        // 如果是可导出的变量(public),则获取其json字段
        tag := sf.Tag.Get("json")
        // 注释掉其他逻辑...
    } 
    // 注释掉其他逻辑... 
}

文章推荐:

如果你想每天学习一个知识点?