golang []byte轉json和json轉[]byte

json轉[]bytejson

paymentData := WxPayData{
		ApiKey: __notify.ApiKey,
		Appid:  __notify.Data.Appid,
		MchId:  __notify.Data.MchId,
	}
	paymentDataBuf, _ := json.Marshal(&paymentData)

上圖中的paymentData是一個json結構,使用json.Marshal轉換完以後的paymentDataBuf是一個[]byte結構url

 

[]byte轉json指針

data := goo.NewHttp().SetUrl(__sns_oauth2_url).Get()

	__snsOauth2Response := snsOauth2Response{}
	if err := json.Unmarshal(data, &__snsOauth2Response); err != nil {
		return nil, err
	}

首先定義了一個json結構,如上圖中的__snsOauth2Response,他的具體結構以下code

type snsOauth2Response struct {
	AccessToken  string        `json:"access_token"`
	ExpireIn     time.Duration `json:"expire_in"`
	Openid       string        `json:"openid"`
	Unionid      string        `json:"unionid"`
	RefreshToken string        `json:"refresh_token"`
	Scope        string        `json:"scope"`
}

而後用json.Unmarshal把[]byte類型的data轉換成json結構的__snsOauth2Response,記得要加指針&token

定義的結構除了struct,也能夠是map[string]string,或者interface{}string

相關文章
相關標籤/搜索