如何將 JSON 解組為包含 2 個字段(UserName和Name)的結(jié)構(gòu),其中包含相同的 JSON 標記名稱(name)?package mainimport ( "encoding/json" "fmt")type User struct { UserName string `json:"name,omitempty"` Name string `json:"name,omitempty"`}func main() { data := []byte(` { "name":"kishore" } `) user := &User{} err := json.Unmarshal(data, &user) if err != nil { panic(err) } fmt.Printf("value of user : %+v\n", user)}實際輸出: value of user : &{UserName: Name:}預期輸出: value of user : &{UserName:kishore Name:kishore}如何獲得UserNameandName字段填充kishore?當我查看Json的源代碼時,我發(fā)現(xiàn)如果 2 個頂級字段具有相同的標簽名稱,它們就會丟棄。但是代碼中的這條評論讓我想到是否有辦法標記兩者either both tagged or neither taggedfunc dominantField(fields []field) (field, bool) { // The fields are sorted in increasing index-length order, then by presence of tag. // That means that the first field is the dominant one. We need only check // for error cases: two fields at top level, either both tagged or neither tagged. if len(fields) > 1 && len(fields[0].index) == len(fields[1].index) && fields[0].tag == fields[1].tag { return field{}, false } return fields[0], true}游樂場鏈接: https: //play.golang.org/p/TN9IQ8lFR6a
Golang 具有相同 json 標簽名稱的多個字段
寶慕林4294392
2022-06-13 10:54:31