本篇文章给大家分享《golang json marshal 的疑问》,覆盖了Golang的常见基础知识,其实一个语言的全部知识点一篇文章是不可能说完的,但希望通过这些问题,让读者对自己的掌握程度有一定的认识(B 数),从而弥补自己的不足,更好的掌握它。
问题内容
我调用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)
}
}
结构体里的字段开头大写才能导出。
文中关于golang的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《golang json marshal 的疑问》文章吧,也可关注golang学习网公众号了解相关技术文章。
本文内容来源于互联网,如有侵权请联系删除。
