Casting interface{} to struct in json encoding

huangapple go评论143阅读模式
英文:

Casting interface{} to struct in json encoding

问题

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

  1. type Config struct {
  2. Application interface{} `json:"application"`
  3. }
  4. type MysqlConf struct {
  5. values map[string]string `json:"mysql"`
  6. }
  7. func main() {
  8. const jsonStr = `
  9. {
  10. "application": {
  11. "mysql": {
  12. "user": "root",
  13. "password": "",
  14. "host": "localhost:3306",
  15. "database": "db"
  16. }
  17. }
  18. }`
  19. dec := json.NewDecoder(strings.NewReader(jsonStr))
  20. var c Config
  21. c.Application = &MysqlConf{}
  22. err := dec.Decode(&c)
  23. if err != nil {
  24. fmt.Println(err)
  25. }
  26. }

我不知道为什么结果的结构体是空的。你有什么想法吗?

英文:

I have such code: http://play.golang.org/p/aeEVLrc7q1

  1. type Config struct {
  2. Application interface{} `json:"application"`
  3. }
  4. type MysqlConf struct {
  5. values map[string]string `json:"mysql"`
  6. }
  7. func main() {
  8. const jsonStr = `
  9. {
  10. "application": {
  11. "mysql": {
  12. "user": "root",
  13. "password": "",
  14. "host": "localhost:3306",
  15. "database": "db"
  16. }
  17. }
  18. }`
  19. dec := json.NewDecoder(strings.NewReader(jsonStr))
  20. var c Config
  21. c.Application = &MysqlConf{}
  22. err := dec.Decode(&c)
  23. if err != nil {
  24. fmt.Println(err)
  25. }
  26. }

And I don't know why resulting struct is empty. Do you have any ideas?

答案1

得分: 5

你在MysqlConf结构体中没有导出values字段,所以json包无法使用它。使用大写字母来命名变量以解决这个问题:

  1. type MysqlConf struct {
  2. Values map[string]string `json:"mysql"`
  3. }
英文:

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:

  1. type MysqlConf struct {
  2. Values map[string]string `json:"mysql"`
  3. }

huangapple
  • 本文由 发表于 2014年6月25日 21:11:20
  • 转载请务必保留本文链接:https://go.coder-hub.com/24409665.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定