Decoding json in Golang

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

Decoding json in Golang

问题

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

package main

import (
	"encoding/json"
	"fmt"
)

type ApiParams struct {
	AccessToken string `json:"access_token"`
	TokenType   string `json:"token_type"`
	ExpiresIn   int64  `json:"expires_in"`
}

func main() {
	data := `{
		"access_token": "asdfasdf",
		"token_type": "bearer",
		"expires_in": 5173885
	}`

	var apiParams ApiParams
	err := json.Unmarshal([]byte(data), &apiParams)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(apiParams)
}

希望这可以帮助到你!

英文:

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

package main

import (
	"encoding/json"
	"fmt"
)

type ApiParams struct {
	AccessToken string `json:access_token`
	TokenType   string `json:token_type`
	ExpiresIn   int64  `json:expires_in`
}

func main() {
	data := `{
    		"access_token": "asdfasdf",
    		"token_type": "bearer",
    		"expires_in": 5173885
	}`

	var apiParams ApiParams
	err := json.Unmarshal([]byte(data), &apiParams)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(apiParams)
}

答案1

得分: 2

将标签添加双引号:

type ApiParams struct {
    AccessToken string `json:"access_token"`
    TokenType   string `json:"token_type"`
    ExpiresIn   int64  `json:"expires_in"`
}
英文:

Add double quotes to the tags:

type ApiParams struct {
    AccessToken string `json:"access_token"`
    TokenType   string `json:"token_type"`
    ExpiresIn   int64  `json:"expires_in"`
}

答案2

得分: 2

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

type ApiParams struct {
    AccessToken string `json:"access_token"`
    TokenType   string `json:"token_type"`
    ExpiresIn   int64  `json:"expires_in"`
}
英文:

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

type ApiParams struct {
    AccessToken string `json:"access_token"`
    TokenType   string `json:"token_type"`
    ExpiresIn   int64  `json:"expires_in"`
}

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:

确定