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.

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

报告相同问题?

悬赏问题

  • ¥100 Jenkins自动化部署—悬赏100元
  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算
  • ¥15 java如何提取出pdf里的文字?