投射界面{}以json编码结构化 [英] Casting interface{} to struct in json encoding

查看:106
本文介绍了投射界面{}以json编码结构化的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码: http://play.golang.org/p/aeEVLrc7q1

 类型配置结构{
应用程序接口{}`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)
}
}

我不知道为什么导致st ruct是空的。你有什么想法吗?

您没有将导出 MysqlConf 结构,所以 json 包不能使用它。在变量名中使用大写字母来做到这一点:

  type MysqlConf struct {
值map [string] string `json:mysql`
}


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?

解决方案

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编码结构化的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆