Go 語言中 encoding/json 包可以很方便的將結構體、數(shù)組、字典轉換為 json 字符串。
引用
import "encoding/json"
解析語法
// v 傳入結構體、數(shù)組等實例變量 // []byte 字節(jié)數(shù)組 // error 可能會有的錯誤 func Marshal(v interface{}) ([]byte, error)
反解析
// []byte 字節(jié)數(shù)組 // v 傳入結構體、數(shù)組等實例變量的指針地址 // error 可能會有的錯誤 func Unmarshal(data []byte, v interface{}) error
代碼
package main // https://golang.org/pkg/encoding/json/ // https://cloud.tencent.com/developer/section/1141542#stage-100023262 import ( "fmt" "encoding/json" ) type User struct { Id int `json:"id"` Name string `json:"name"` } func main() { // 字符串解析為結構體 s := `{"id": 1, "name": "wxnacy"}` var user User // 將字符串反解析為結構體 json.Unmarshal([]byte(s), user) fmt.Println(user) // {1 wxnacy} var d map[string]interface{} // 將字符串反解析為字典 json.Unmarshal([]byte(s), d) fmt.Println(d) // map[id:1 name:wxnacy] s = `[1, 2, 3, 4]` var a []int // 將字符串反解析為數(shù)組 json.Unmarshal([]byte(s), a) fmt.Println(a) // [1 2 3 4] // 將結構體解析為字符串 b, e := json.Marshal(user) fmt.Println(e) fmt.Println(string(b)) // {"id":1,"name":"wxnacy"} b, e = json.Marshal(a) fmt.Println(string(b), e) // [1,2,3,4] nil> b, e = json.Marshal(d) fmt.Println(string(b), e) // {"id":1,"name":"wxnacy"} nil> }
以上這篇Go 結構體、數(shù)組、字典和 json 字符串的相互轉換方法就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持腳本之家。