package main import (
"encoding/json" "fmt" )
func main ( ) {
str:=`{"repositories":["heapster","mysql","zeppelin"]}` byteStr:=[]byte(str) type Repository struct{ repositories []string } var repo Repository json. Unmarshal ( byteStr , &repo ) fmt.Println(repo)
}
最后輸出為空的數(shù)組,請問哪里錯了???
擁有18年軟件開發(fā)和IT教學(xué)經(jīng)驗。曾任多家上市公司技術(shù)總監(jiān)、架構(gòu)師、項目經(jīng)理、高級軟件工程師等職務(wù)。 網(wǎng)絡(luò)人氣名人講師,...
你這個是struct的item都是私有的,只能當(dāng)前package調(diào)用,要是傳給json的話,就會讀取不到定義struct的時候大寫首字母即可
func?main(){ str:=`{"repositories":["heapster","mysql","zeppelin"]}` byteStr:=[]byte(str) type?Repository?struct{ ????Repositories?[]string } var?repo?Repository json.?Unmarshal?(?byteStr?,?&repo?) fmt.Println(repo)? }
至于樓上說的struct加tag描述,那是為了字段名不一致使用的,默認(rèn)情況下解析首字母大寫會自動檢測小寫的,下面這種情況就需要定義tag表述
func?main(){ str:=`{"test_repositories":["heapster","mysql","zeppelin"]}` byteStr:=[]byte(str) type?Repository?struct{ ????Repositories?[]string?`json:"test_repositories"` } var?repo?Repository json.?Unmarshal?(?byteStr?,?&repo?) fmt.Println(repo)? }
type?Repository?struct{ ????Repositories?[]string?`json:"repositories"` }
可導(dǎo)出字段才可以被反射賦值