json - 在 Golang 中解析 JSON 时出错

标签 json parsing go

我开发这段代码:

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 使多个客户端填写了一个字段,而不是一个客户端填写了所有字段

参见示例:https://play.golang.org/p/oY7SppWNDC

关于json - 在 Golang 中解析 JSON 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35589541/

相关文章:

java - SQLContext.read() Spark 中的 NullPointerException

php - 在 iOS 中进行 JSON 序列化时失败,但通过浏览器访问时 API 正常

javascript - 无法找到聊天消息的 Steam UMQID

sql-server - Go语言: JOIN sql with two different connections/databases

javascript - 如何在 d3.js 中保留具有唯一 ID 的行一次

json - 在 JSend 规范中,失败和错误有什么区别?

java - 从 Wordpress 提要中解析 Java 中的 XML

bash - 如何汇总字符串中的数字并生成单个汇总字符串

c# - 自定义标记解析器不处理换行符

go - 将带有 null 的 bigquery 行映射到结构后出现异常