package main import ( "encoding/json" "fmt" "os" ) type ConfigStruct struct { Expires_in string `json:"expires_in"` Refresh_token string `json:"refresh_token"` Access_token string `json:"access_token "` Session_secret string `json:"session_secret "` Scope string `json:"scope "` Session_key string `json:"session_key "` } func main() { jsonStr := `{expires_in": 2592000, "refresh_token": "22.1e1285e0ab8cb8e4453d31cb53774369.315360000.1756022822.2605827041 - 6701125 ","access_token ":"21.9 ab5cd9698424e9f56e0a8488aabd9f0.2592000.1443254822.2605827041-6701125 ","session_secret ":"9985 f4f820286dae4c532fbfb111dc91 ", "session_key ":"9 mnRfVsV + 0 JrbIB15 + MNzaUm3YyLsqOrRWvBODzwG3KK5RaRGMlLx + smjfkMLmrwlvItGhDln9OxrNnrjJZ3yIUTZ2K0zkJkEA == ","scope ":"basic"}` // to map var data map[string]interface{} if err := json.Unmarshal([]byte(jsonStr), &data); err == nil { fmt.Println(data) } //json to struct var config ConfigStruct if err := json.Unmarshal([]byte(jsonStr), &config); err == nil { fmt.Println(config) fmt.Println(config.Access_token) } //struct to jsonstr if b, err := json.Marshal(config); err == nil { fmt.Println(string(b)) } //map to jsonstr enc := json.NewEncoder(os.Stdout) enc.Encode(data) //array to jsonstr arr := []string{"c", "c++", "java", "python", "javaScript", "nodejs", "golang"} lang, err := json.Marshal(arr) if err == nil { fmt.Println(string(lang)) } //json to []string var wo []string if err := json.Unmarshal(lang, &wo); err == nil { fmt.Println(wo) } }
时间: 2024-10-05 05:07:56