Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/go/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Golang:多结构marshall问题:json格式_Json_Go_Struct_Marshalling - Fatal编程技术网

Golang:多结构marshall问题:json格式

Golang:多结构marshall问题:json格式,json,go,struct,marshalling,Json,Go,Struct,Marshalling,对于以下代码,我得到了错误: 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)

对于以下代码,我得到了错误:

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)
        }
}

在我的输出中,我试图实现以下目标:

{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)
带有静态值的示例程序


注意:
type
是language关键字,不要将其用作变量名。

昨天您发布了关于XML解组的问题以及RPC XML的问题。我已经分析并回答了你的问题。你没有接受答案,只是简单地回答“谢谢,我太蠢了”,然后删除了这个问题。我建议以后不要这样做,这对社区不好。@jeevatkm:这绝对是我这一辈人的一个无意识错误。它现在回来了。道歉!谢谢,没问题。我只是想引起你的注意。顺便说一句,我希望这个答案解决了你的问题。请接受SO中的答案。引用的文件是否为
int2.go
?哪一行是156?编译器错误会告诉你出了什么问题,但是如果没有任何上下文,任何人都无法帮助你。@Adrian updated!这修复了错误,但是输出是这样的:{A:[{X:1,Y:2}]},{A:[{X:1,Y:2}]},{A:[{X:1,Y:2}]}我正在尝试生成类似于:{A:{X:1,Y:2},{X:2,Y:2},{X:2,Y:2}的内容,应该是var bj[]B吗?不客气,添加了golang play链接供参考。
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)