Golang:多个结构编组问题:json 格式
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}}}
Struct 调用另一个 struct 以获取上面的模式。
你这行好像有问题-
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
为语言关键字,请勿用作变量名。
对于以下代码,我收到错误:
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}}}
Struct 调用另一个 struct 以获取上面的模式。
你这行好像有问题-
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
为语言关键字,请勿用作变量名。