我开发这段代码:
package main
import (
"fmt"
"io/ioutil"
"encoding/json"
)
type Client struct{
host string
key string
secrete string
username string
password string
}
type Config struct{
Client []Client
}
func main(){
content, err := ioutil.ReadFile("conf2.json")
if err!=nil{
fmt.Print("Error:",err)
}
var conf Config
err=json.Unmarshal(content, &conf)
if err!=nil{
fmt.Print("Error:",err)
}
json.Unmarshal(content, &conf)
fmt.Println(conf.Client[0].host)
}
从我的 json 中解析并打印第一个主机详细信息,如下所示:
{ "Client" : [ {"host":"192.168.1.2"},
{"key":"abcdf"}, {"secrete":"9F6w"}, {"username":"user"}, {"password":"password"} ] }
但是我得到一个空字符串。有人知道原因吗?
最佳答案
需要解决的三件事:
- json.Unmarshal 要求结构字段大写才能导出,否则将被忽略
- 您需要
json:"<name>"
字段后的说明符,以便解码器知道结构字段到 json 的映射 - 您的 json 使多个客户端填写了一个字段,而不是一个客户端填写了所有字段
关于json - 在 Golang 中解析 JSON 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35589541/