This is a creation in Article, where the information may have evolved or changed.
JSON is now a very common way of data passing, and go itself integrates the generation and parsing of JSON
Introduction Package
import { "bytes" "encoding/json"}
Analytical
Define json
the corresponding entity class, which is exactly the structure
type GoAccessToken struct { AccessToken string ExpiresIn int}
Create a reference to the struct body
goAccessToken := &GoAccessToken{}
Unmarshal
parse the string by going to json
err := json.Unmarshal(str, goAccessToken)最终的 goAcessToken 为解析后的对象
If you find that the member variable in the object does not have a value, check that the first letter of the member variable is uppercase, and note that the key value of the JSON string is case-insensitive and only the first-capitalized member variable is parsed out of the value
Generate JSON
Define json
the corresponding entity class, which is exactly the structure
type GoAccessToken struct { AccessToken string ExpiresIn int}
Create a reference to the struct and assign a value
goAccessToken := &GoAccessToken{ "这是token值", 7200,}
By Marshal
going to generate a json
string
str, err := json.Marshal(goAccessToken)str 即为生成的 json 字符串
The first letter of the member variable must be capitalized, otherwise the variable will not be generated in the JSON string