首页 > golang json marshal 的疑问

golang json marshal 的疑问

我调用json.Marshal的时候,程序的结果和我的预期不一致, 谁能够帮忙解释下原因
程序的输出结果是:

{} {[{[{content lvl 1}] [{[{content lvl 2}] []}]}]} content lvl 1

json编码永远是空的。但是 root 下面的数据节点明明都还有呀?

package main

import (
    "encoding/json"
    "fmt"
)

type Root struct {
    entries []Entries
}

type Entries struct {
    contents []Content
    entries  []Entries
}

type Content struct {
    title string
}

func main() {
    c1 := Content{}
    c1.title = "content lvl 1"

    e1 := Entries{}
    e1.contents = append(e1.contents, c1)

    e2 := Entries{}
    c2 := Content{title: "content lvl 2"}
    e2.contents = append(e2.contents, c2)

    e1.entries = append(e1.entries, e2)

    root := Root{}
    root.entries = append(root.entries, e1)

    if out, err := json.Marshal(&root); err != nil {
        fmt.Println("error")
    } else {
        fmt.Println(string(out), root, root.entries[0].contents[0].title)
    }
}

package main

import (
    "encoding/json"
    "fmt"
)

type Root struct {
    Entries []Entries
}

type Entries struct {
    Contents []Content
    Entries  []Entries
}

type Content struct {
    Title string
}

func main() {
    c1 := Content{}
    c1.Title = "content lvl 1"

    e1 := Entries{}
    e1.Contents = append(e1.Contents, c1)

    e2 := Entries{}
    c2 := Content{Title: "content lvl 2"}
    e2.Contents = append(e2.Contents, c2)

    e1.Entries = append(e1.Entries, e2)

    root := Root{}
    root.Entries = append(root.Entries, e1)

    if out, err := json.Marshal(root); err != nil {
        fmt.Println("error")
    } else {
        fmt.Println(string(out), root, root.Entries[0].Contents[0].Title)
    }
    
}

结构体里的字段开头大写才能导出。


同样遇到了这样的问题,把struct中每个元素的的key都改成首字母大写之后就OK了。

【热门文章】
【热门文章】