doushi5913
2017-10-15 19:30
浏览 66

JSON解码器会忽略结构字段标记?

I'm using the Decoder from package encoding/json to decode a JSON configuration file into a struct. The field names have a different case (lowercase first character in struct because of visibility concerns) in the file and struct so I'm using struct field tags as described in the documentation. The Problem is that Decoder seems to ignore these tags and the struct fields are empty. Any ideas what's wrong with my code?

config.json

{
    "DataSourceName": "simple-blog.db"
}

Config struct

type Config struct {
     dataSourceName string `json:"DataSourceName"`
}

Loading config

func loadConfig(fileName string) {
    file, err := os.Open(fileName)
    if err != nil {
        log.Fatalf("Opening config file failed: %s", err)
    }
    defer file.Close()

    decoder := json.NewDecoder(file)
    config = &Config{} // Variable config is defined outside
    err = decoder.Decode(config)
    if err != nil {
        log.Fatalf("Decoding config file failed: %s", err)
    }

    log.Print("Configuration successfully loaded")
}

Usage

loadConfig("config.json")
log.Printf("DataSourceName: %s", config.dataSourceName)

Output

2017/10/15 21:04:11 DB Name: 
  • 写回答
  • 关注问题
  • 收藏
  • 邀请回答

1条回答 默认 最新

  • duanjiangzhi6851 2017-10-15 19:34
    已采纳

    You need to export your dataSourceName field as encoding/json package requires them to be so

    已采纳该答案
    打赏 评论