问题
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