简体   繁体   English

Golang:多重结构马歇尔号问题:json格式

[英]Golang: Multiple structs marshall issue: json format

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. 结构调用另一个结构以获取上面的模式。

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 具有静态值的示例程序https://play.golang.org/p/a2ZDV8lgWP

Note: type is language keyword, do not use it as variable name. 注意: type是语言关键字,请勿将其用作变量名。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM