Проблемы с преобразованием текста в структуру

Попытка разобрать текст 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:[]}

person linuxfan    schedule 22.02.2017    source источник


Ответы (1)


Ваши структуры имеют структуру, отличную от структуры 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

person JimB    schedule 22.02.2017