2017-02-22 25 views
0

嘗試將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:[]} 

回答

3

您的結構與您提供的json有不同的結構。編組在您的示例的結構會導致JSON看起來像:

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

在您的示例中的JSON可以直接與CmdUnit.DescriptionCmdUnit.Desc的微小變化解組到map[string][]CmdUnit{}

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

+0

感謝很多JimB – linuxfan