Marshal返回我结构的空json

时间:2015-12-05 16:53:22

标签: json go marshalling

我正在处理一个代码,该代码将一个主题库扫描到一个结构中,以便将它导出到json。

目前,我的代码使用ScanDir函数精确扫描了一个剧目,但是当我尝试对我的结构进行制作时,它只返回{}

// file's struct
type Fic struct {
    nom     string    `json:"fileName"`
    lon     int64     `json:"size"`
    tim     time.Time `json:"lastFileUpdate"`
    md5hash []byte    `json:"md5"`
}

// folder's struct
type Fol struct {
    subFol []Fol     `json:"listFolders"`
    files  []Fic     `json:"listFiles"`
    nom    string    `json:"folderName"`
    tim    time.Time `json:"lastFolderUpdate"`
}

func main() {
    var root Fol
    err := ScanDir("./folder", &root)   // scan a folder and fill my struct
    check(err)
    b, err := json.Marshal(root)
    check(err)
    os.Stdout.Write(b)
}

func check(err error) {
if err != nil {
    fmt.Fprintf(os.Stderr, "Fatal error : %s", err.Error())
    os.Exit(1)
}

1 个答案:

答案 0 :(得分:5)

为了编组和解组json,struct的fields / property需要是公共的。要使struct public的字段/属性,它应该以大写字母开头。在你的所有领域都是小写的。

type Fic struct {
    Nom     string    `json:"fileName"`
    Lon     int64     `json:"size"`
    Tim     time.Time `json:"lastFileUpdate"`
    Md5hash []byte    `json:"md5"`
}

// folder's struct
type Fol struct {
    SubFol []Fol     `json:"listFolders"`
    Files  []Fic     `json:"listFiles"`
    Nom    string    `json:"folderName"`
    Tim    time.Time `json:"lastFolderUpdate"`
}
相关问题