在json编码中将接口{}转换为struct

Sła*_*osz 1 json go

我有这样的代码: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)
    }
}
Run Code Online (Sandbox Code Playgroud)

我不知道为什么结果结构是空的.你有什么想法?

jul*_*enc 5

您没有valuesMysqlConf结构中导出,因此json包无法使用它.在变量名中使用大写字母来执行此操作:

type MysqlConf struct {
    Values map[string]string `json:"mysql"`
}
Run Code Online (Sandbox Code Playgroud)