Marshal returns empty json of my struct

為{幸葍}努か 提交于 2019-12-20 05:43:07

问题


I'm working on a code that scan a repertory into a struct in order to export it to json.

Currently, my code scans finely a repertory with the ScanDir function, but when I try to Marshal my struct it only returns {}.

// 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:


In order to marshal and unmarshal json, fields/property of struct needs to be public. To make the field/property of struct public it should start with Upper Case. In your all the fields are in lower case.

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"`
}


来源:https://stackoverflow.com/questions/34108129/marshal-returns-empty-json-of-my-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!