Casting interface{} to struct in json encoding

huangapple go评论103阅读模式
英文:

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"`
}

huangapple
  • 本文由 发表于 2014年6月25日 21:11:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/24409665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定