Decoding json in Golang

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

Decoding json in Golang

问题

我无法解决你的代码问题,但我可以帮你翻译代码。以下是你提供的代码的翻译:

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type ApiParams struct {
  7. AccessToken string `json:"access_token"`
  8. TokenType string `json:"token_type"`
  9. ExpiresIn int64 `json:"expires_in"`
  10. }
  11. func main() {
  12. data := `{
  13. "access_token": "asdfasdf",
  14. "token_type": "bearer",
  15. "expires_in": 5173885
  16. }`
  17. var apiParams ApiParams
  18. err := json.Unmarshal([]byte(data), &apiParams)
  19. if err != nil {
  20. fmt.Println(err)
  21. }
  22. fmt.Println(apiParams)
  23. }

希望这可以帮助到你!

英文:

I cannot figure out what's wrong in my code to decode this json. It returns an empty struct. Go playground here: http://play.golang.org/p/K8WznLT5M0

  1. package main
  2. import (
  3. "encoding/json"
  4. "fmt"
  5. )
  6. type ApiParams struct {
  7. AccessToken string `json:access_token`
  8. TokenType string `json:token_type`
  9. ExpiresIn int64 `json:expires_in`
  10. }
  11. func main() {
  12. data := `{
  13. "access_token": "asdfasdf",
  14. "token_type": "bearer",
  15. "expires_in": 5173885
  16. }`
  17. var apiParams ApiParams
  18. err := json.Unmarshal([]byte(data), &apiParams)
  19. if err != nil {
  20. fmt.Println(err)
  21. }
  22. fmt.Println(apiParams)
  23. }

答案1

得分: 2

将标签添加双引号:

  1. type ApiParams struct {
  2. AccessToken string `json:"access_token"`
  3. TokenType string `json:"token_type"`
  4. ExpiresIn int64 `json:"expires_in"`
  5. }
英文:

Add double quotes to the tags:

  1. type ApiParams struct {
  2. AccessToken string `json:"access_token"`
  3. TokenType string `json:"token_type"`
  4. ExpiresIn int64 `json:"expires_in"`
  5. }

答案2

得分: 2

你的注释是错误的。你需要在JSON属性名称周围加上引号,像这样:

  1. type ApiParams struct {
  2. AccessToken string `json:"access_token"`
  3. TokenType string `json:"token_type"`
  4. ExpiresIn int64 `json:"expires_in"`
  5. }
英文:

Your annotations are wrong.. You need quotes around the json property names like;

  1. type ApiParams struct {
  2. AccessToken string `json:"access_token"`
  3. TokenType string `json:"token_type"`
  4. ExpiresIn int64 `json:"expires_in"`
  5. }

huangapple
  • 本文由 发表于 2015年4月30日 00:44:27
  • 转载请务必保留本文链接:https://go.coder-hub.com/29949777.html
匿名

发表评论

匿名网友

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

确定