json.Unmarshal到对象的json字符串为空结果 [英] json.Unmarshal json string to object is empty result
本文介绍了json.Unmarshal到对象的json字符串为空结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个非常简单的程序,如下所示:
I've got a very simple program like this:
package main
import (
"encoding/json"
"fmt"
)
type RunCommand struct{
level string `json:"level"`
caller string `json:"caller"`
msg string `json:"msg"`
cmd string `json:"cmd"`
}
func main() {
content := `{"level":"info","caller":"my.go:10","msg":"run","cmd":"--parse"}`
runCommand := RunCommand{}
e := json.Unmarshal([]byte(content), &runCommand)
if e != nil {
fmt.Println("Unmarshal error")
}
fmt.Println(runCommand.level)
}
我希望可以将"content"内的所有json字段解析为"runCommand"对象,但实际上,最终的"fmt.Println"不会打印任何内容.我在哪里弄错了?
I wish that I could parse out all the json fields inside "content" into "runCommand" object, but actually, the final "fmt.Println" prints nothing. Where did I get wrong?
推荐答案
您必须具有如下导出的字段:
You have to have exported fields, like this:
type RunCommand struct{
Level string `json:"level"`
Caller string `json:"caller"`
Msg string `json:"msg"`
Cmd string `json:"cmd"`
}
,现在您可以使用:fmt.Println(runCommand.Level)
否则json.Unmarshal
将忽略未导出的字段.
and now you can use: fmt.Println(runCommand.Level)
otherwise json.Unmarshal
will ignore non-exported fields.
这篇关于json.Unmarshal到对象的json字符串为空结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文