英文:
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}}}
结构体调用另一个结构体以获得上述模式。
英文:
For the following code, I get the error:
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
In my output, I am trying to achieve something like this:
{A: {{X:1 ,Y: 2}, {X:2 ,Y: 2}, {X: 2,Y: 2}}}
Struct calling another struct to get the pattern above.
答案1
得分: 1
看起来你在这一行有问题:
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 是语言关键字,请不要将其用作变量名。
英文:
It seems you have problem at this line-
t := A{B_j: []B{X: name.text, Y: name.type }}
You're not creating a slice properly. Try following-
t := A{B_j: []B{{X: name.text, Y: name.type}}}
Let's do it better way-
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)
Sample program with static values https://play.golang.org/p/a2ZDV8lgWP
Note: type is language keyword, do not use it as variable name.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论