Golang中JSON序列化无输出问题排查
Golang中JSON序列化无输出问题排查 谁能告诉我为什么这段代码不工作?我已经将代码简化到一个基本示例。我试图将几个变量存储在一个结构体中,然后将整个结构体以JSON格式输出。
package main
import (
"fmt"
"encoding/json"
"time"
"log"
)
type DiskSpaceOutput struct {
text string
last_updated string
}
func main() {
var JSONOutput DiskSpaceOutput
JSONOutput.last_updated = fmt.Sprintf(time.Now().Format(time.RFC3339))
JSONOutput.text = string("test")
fmt.Println(JSONOutput.last_updated)
JSONOutputText, err := json.Marshal(JSONOutput)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(JSONOutputText),err)
}
我得到的输出是:
2009-11-10T23:00:00Z
{} <nil>
Program exited.
我不明白为什么JSONOutputText是{},而不是以JSON格式显示结构体中的数据。
上述代码在Go Playground的链接:https://play.golang.org/p/e2f7uArQ71I
更多关于Golang中JSON序列化无输出问题排查的实战教程也可以访问 https://www.itying.com/category-94-b0.html
2 回复
JSON 无法识别未导出的字段。你需要将它们导出。
更多关于Golang中JSON序列化无输出问题排查的实战系列教程也可以访问 https://www.itying.com/category-94-b0.html
问题在于结构体字段的可见性。在Go语言中,只有首字母大写的字段才会被encoding/json包导出并进行JSON序列化。
将结构体字段改为大写即可:
package main
import (
"encoding/json"
"fmt"
"log"
"time"
)
type DiskSpaceOutput struct {
Text string `json:"text"`
LastUpdated string `json:"last_updated"`
}
func main() {
var JSONOutput DiskSpaceOutput
JSONOutput.LastUpdated = time.Now().Format(time.RFC3339)
JSONOutput.Text = "test"
fmt.Println(JSONOutput.LastUpdated)
JSONOutputText, err := json.Marshal(JSONOutput)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(JSONOutputText))
}
输出结果:
2009-11-10T23:00:00Z
{"text":"test","last_updated":"2009-11-10T23:00:00Z"}
如果需要保持JSON中的字段名为小写,可以使用结构体标签:
type DiskSpaceOutput struct {
Text string `json:"text"`
LastUpdated string `json:"last_updated"`
}
这样JSON序列化时会使用text和last_updated作为字段名,而不是Text和LastUpdated。

