我调用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)
}
}
结构体里的字段开头大写才能导出。