麻烦将文本解组为struct

时间:2017-02-22 23:48:00

标签: go encoding

尝试将json文本解组为我自己的结构。我的结构定义看似正确,但json.Unmarshal没有返回任何内容。

package main

import (
    "encoding/json"
    "fmt"
)

type CmdUnit struct {
    Command     string
    Description string
}

type CmdList struct {
    ListOfCommands []CmdUnit
}

type OneCmdList struct {
    Area    string
    CmdList CmdList
}

type AllCommands struct {
    AllAreas []OneCmdList
}

func main() {
    jsonTxt := `
    {
        "Area1": [{
                "Command": "cmd1",
                "Desc": "cmd1 desc"
        }, {
                "Command": "cmd2",
                "Desc": "cmd2 desc"
        }],
        "Area2": [{
                "Command": "cmd1",
                "Desc": "cmd1 desc"
        }]

}
`
    cmds := AllCommands{}
    if err := json.Unmarshal([]byte(jsonTxt), &cmds); err != nil {
        fmt.Println("Failed to unmarshal:", err)
    } else {
        fmt.Printf("%+v\n", cmds)
    }
}


$ go run j.go
{AllAreas:[]}

1 个答案:

答案 0 :(得分:3)

你的结构与你提供的json有不同的结构。在您的示例中编组结构将导致json看起来像:

{
  "AllAreas": [
    {
      "Area": "Area1",
      "CmdList": {
        "ListOfCommands": [
          {
            "Command": "cmd1",
            "Description": "cmd1 desc"
          },
          {
            "Command": "cmd2",
            "Description": "cmd2 desc"
          }
        ]
      }
    }
  ]
}

您的示例中的json可以直接解组为map[string][]CmdUnit{},并将CmdUnit.Description稍微更改为CmdUnit.Desc

cmds := map[string][]CmdUnit{}
if err := json.Unmarshal(jsonTxt, &cmds); err != nil {
    log.Fatal("Failed to unmarshal:", err)
}
fmt.Printf("%+v\n", cmds)

https://play.golang.org/p/DFLYAfNLES