元帅返回空结构的JSON [英] Marshal returns empty json of my struct

查看:76
本文介绍了元帅返回空结构的JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述



目前,我的代码很好地扫描了一个存储库中的代码库 ScanDir 函数,但是当我尝试编制结构时,它只返回 {}

  //文件结构
类型Fic结构{
nom字符串`json:文件名`
lon int64`json :size`
tim time.Time`json:lastFileUpdate`
md5hash [] byte`json:md5`
}

//文件夹的结构
类型Fol结构{
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)//扫描文件夹并填写我的结构
check(err)
b,err:= json.Marshal(root)
check(err )
os.Stdout.W rite(b)
}

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


解决方案

为了编组和解组json,结构的fields / property需要是公共的。为了使struct的field / property成为public,它应该以大写字母开头。

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

//文件夹的结构
类型Fol结构{
SubFol [] Fol`json:listFolders`
文件[] Fic`json:listFiles`
Nom string`json:folderName`
Tim time.Time`json:lastFolderUpdate``
}


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)
}

解决方案

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

这篇关于元帅返回空结构的JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆