[英]Golang: Multiple structs marshall issue: json format
對於以下代碼,我得到了錯誤:
type A struct{
B_j []B `json:"A"`
}
type B struct
{
X string
Y string
}
func main() {
xmlFile, _ := os.Open("test.xml")
b, _ := ioutil.ReadAll(xmlFile)
var t root
err2 := xml.Unmarshal(b, &rpc)
if err2 != nil {
fmt.Printf("error: %v", err2)
return
}
for _, name := range t.name{
t := A{B_j : []B{X : name.text, Y: name.type }} // line:#25
s, _ := json.MarshalIndent(t,"", " ")
os.Stdout.Write(s)
}
}
# command-line-arguments
./int2.go:25: undefined: X
./int2.go:25: cannot use name.Text (type string) as type B in array or slice literal
./int2.go:25: undefined: Y
./int2.go:25: cannot use name.type (type string) as type B in array or slice literal
在我的輸出中,我正在嘗試實現以下目標:
{A: {{X:1 ,Y: 2}, {X:2 ,Y: 2}, {X: 2,Y: 2}}}
結構調用另一個結構以獲取上面的模式。
看來您在這條線上有問題-
t := A{B_j: []B{X: name.text, Y: name.type }}
您沒有正確創建切片。 嘗試以下-
t := A{B_j: []B{{X: name.text, Y: name.type}}}
讓我們做一個更好的方法-
var bj []B
for _, name := range t.name{
bj = append(bj, B{X: name.text,Y: name.type})
}
t := A{B_j: bj}
s, _ := json.MarshalIndent(t,"", " ")
os.Stdout.Write(s)
具有靜態值的示例程序https://play.golang.org/p/a2ZDV8lgWP
注意: type
是語言關鍵字,請勿將其用作變量名。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.