Casting interface{} to struct in json encoding

2020-04-20 12:00发布

问题:

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:

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


标签: json go