duanchouyi6730 2017-06-16 19:09
浏览 60
已采纳

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

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条回答 默认 最新

  • douqiu1604 2017-06-16 19:36
    关注

    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.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 python中transformers可以正常下载,但是没有办法使用pipeline
  • ¥50 分布式追踪trace异常问题
  • ¥15 人在外地出差,速帮一点点
  • ¥15 如何使用canvas在图片上进行如下的标注,以下代码不起作用,如何修改
  • ¥15 Windows 系统cmd后提示“加载用户设置时遇到错误”
  • ¥50 vue router 动态路由问题
  • ¥15 关于#.net#的问题:End Function
  • ¥15 无法import pycausal
  • ¥15 weditor无法连接模拟器Local server not started, start with?
  • ¥20 6-3 String类定义