2017-02-22 4 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とは異なる構造を持っています。

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

あなたの例では、JSONがCmdUnit.DescからCmdUnit.Descriptionのマイナーチェンジでmap[string][]CmdUnit{}に直接非整列化することができます:あなたの例では、構造体をマーシャリングすることのように見えるJSONことになります。

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

関連する問題