英文:
Casting interface{} to struct in json encoding
问题
我有这样的代码:http://play.golang.org/p/aeEVLrc7q1
type Config struct {
Application interface{} `json:"application"`
}
type MysqlConf struct {
values map[string]string `json:"mysql"`
}
func main() {
const jsonStr = `
{
"application": {
"mysql": {
"user": "root",
"password": "",
"host": "localhost:3306",
"database": "db"
}
}
}`
dec := json.NewDecoder(strings.NewReader(jsonStr))
var c Config
c.Application = &MysqlConf{}
err := dec.Decode(&c)
if err != nil {
fmt.Println(err)
}
}
我不知道为什么结果的结构体是空的。你有什么想法吗?
英文:
I have such code: http://play.golang.org/p/aeEVLrc7q1
type Config struct {
Application interface{} `json:"application"`
}
type MysqlConf struct {
values map[string]string `json:"mysql"`
}
func main() {
const jsonStr = `
{
"application": {
"mysql": {
"user": "root",
"password": "",
"host": "localhost:3306",
"database": "db"
}
}
}`
dec := json.NewDecoder(strings.NewReader(jsonStr))
var c Config
c.Application = &MysqlConf{}
err := dec.Decode(&c)
if err != nil {
fmt.Println(err)
}
}
And I don't know why resulting struct is empty. Do you have any ideas?
答案1
得分: 5
你在MysqlConf
结构体中没有导出values
字段,所以json
包无法使用它。使用大写字母来命名变量以解决这个问题:
type MysqlConf struct {
Values map[string]string `json:"mysql"`
}
英文:
You did not export values
in the MysqlConf
structure, so the json
package was not able to use it. Use a capital letter in the variable name to do so:
type MysqlConf struct {
Values map[string]string `json:"mysql"`
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论