Go語言內置encoding/json包支持JSON序列化和反序列化,有以下轉換規則json
- 基本的數據結構映射關係
bool, for JSON booleans float64, for JSON numbers string, for JSON strings []interface{}, for JSON arrays map[string]interface{}, for JSON objects nil for JSON null
- 當有指針出如今數據結構中時,會轉換成指針所指的值。
- chanel,complex和函數不能轉化爲有效的JSON文本
- JSON序列化時,須要定義一個struct結構,支持json tag來擴展功能, 對於未知的json數據結構,支持interface{}做爲接收容器
type Computer struct { Brand string // -:不要解析這個字段 Name string `json: "-"` // omitempty: 字段爲0值時,不要解析 Price float32 `json: "omitempty"` // 能夠替換的字段 IsSupportAntCreditPay bool `json: "huabei,omitempty"` HardwareConfiguration []string }
func NewDecoder(r io.Reader) *Decoder func NewEncoder(w io.Writer) *Encoder
實例
package main import ( "fmt" "encoding/json" ) type Computer struct { Brand string Name string Price float64 // 能夠替換的字段 IsSupportAntCreditPay bool `json: "huabei` HardwareConfiguration []string } func main() { hc := []string{"RTX2080Ti", "i9-9900k", "32G", "DDR4 XMP", "512G SSD"} alienware := Computer { Brand: "Alienware", Name: "外星人ALWS-R4968S", Price: 0, IsSupportAntCreditPay:false, HardwareConfiguration: hc} if b, err := json.Marshal(alienware); err !=nil { return } else { fmt.Println(b) fmt.Println() var computer Computer b := []byte(`{ "Brand": "Alienware", "Name": "外星人ALWS-R4968S", "Price": 0.0, "huabei": "true", "HardwareConfiguration": ["i7-8700K", "GTX 1080Ti"] }`) if err:= json.Unmarshal(b, &computer); err == nil { fmt.Println(computer) fmt.Println() } else { fmt.Println(err) fmt.Println() } var unknowJson interface{} if err:= json.Unmarshal(b, &unknowJson); err == nil { unknowJson, ok := unknowJson.(map[string]interface{}) if ok { for k, v := range unknowJson { switch t := v.(type) { case string: fmt.Println("string:", k, " ", v) case float64: fmt.Println("float:", k, " ", v) case bool: fmt.Println("bool:", k, " ", v) case []interface{}: fmt.Println(k, "is an array:") for i, iv := range t { fmt.Println(i, iv) } default: fmt.Println("unknow type:", k) } } } } } }