繁体   English   中英

golang:解组:json:无法将数组解组为main.MonitorServerInfo类型的Go值

[英]golang : Unmarshal: json: cannot unmarshal array into Go value of type main.MonitorServerInfo

json:无法将数组解组为类型的Go值

配置json:

{
    "monitor_servers_info":[
            {
                "server_info":{
                        "host":"127.0.0.1",
                        "port":28081,
                        "magic":"magic0",
                        "params":"all",
                        "interval":10000
                }
            },
            {
                    "server_info":{
                            "host":"127.0.0.1",
                            "port":28080,
                            "magic":"magic1",
                            "params":"all",
                            "interval":10000
                    }
            }
    ],

    "sentry_server":{
        "host":"127.0.0.1",
        "port":80
    },

    "deadtime":"110000"
}

和我的golang代码是这样的:

type ServerInfo struct {
    Host string     `json:"host"`
    Port int64      `json:"port"`
    Magic string    `json:"magic"`
    Params string   `json:"params"`
    Interval int64  `json:"interval"`
}

type ServerInfoStrap struct {
    ConnInfo ServerInfo  `json:"server_info"`
}

type MonitorServerInfo struct {
    Servers []ServerInfoStrap
}

type SentryServer struct {
    Host string     `json:"host"`
    Port int64      `json:"port"`
}

type ConfigServer struct {
    ServerInfo  MonitorServerInfo  `json:"monitor_servers_info"`
    ConnServer  SentryServer       `json:"sentry_server"`
    DeadTime    string             `json:"deadtime"`
}

json解析代码:

func readFile(filename string) (config ConfigServer, err error) {
    bytes, err := ioutil.ReadFile(filename)
    if err != nil {
        fmt.Println("ReadFile: ", err.Error())
        return
    }

    //bytes, err = StripComments(bytes) //去掉注释
    //if err != nil {
    //  log.Info("Failed to strip comments from json: %s\n", err)
    //  return
    //}

    //xxx := make(map[string]interface{})
    fmt.Println(string(bytes))
    err = json.Unmarshal(bytes, &config)
    if err != nil {
        fmt.Println("Unmarshal: ", err.Error())
        return
    }

    fmt.Println(config)

    return
}

原因是您的MonitorServerInfo类型。 摆脱它,它的工作原理是:

type ConfigServer struct {
    ServerInfo []ServerInfoStrap `json:"monitor_servers_info"`
    ConnServer SentryServer      `json:"sentry_server"`
    DeadTime   string            `json:"deadtime"`
}

游乐场: https : //play.golang.org/p/Prt1j7ePCZ

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM