這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。
下面總結一下go的序列化,通訊中常用的格式:msgpack和json
msgpack
安裝:
go get go get github.com/vmihailenco/msgpack
go install github.com/vmihailenco/msgpack
api:http://godoc.org/github.com/vmihailenco/msgpack
func ExampleEncode() { b, err := msgpack.Marshal(true) fmt.Printf("%v %#v\n", err, b) // Output: <nil> []byte{0xc3}}func ExampleDecode() { var out bool err := msgpack.Unmarshal([]byte{0xc3}, &out) fmt.Println(err, out) // Output: <nil> true}func ExampleMapStringInterface() { in := map[string]interface{}{"foo": uint32(123456789), "hello": "world"} b, err := msgpack.Marshal(in) _ = err var out map[string]interface{} err = msgpack.Unmarshal(b, &out) fmt.Printf("%v %#v\n", err, out) // Output: <nil> map[string]interface {}{"foo":0xfecaefbe, "hello":"world"}}func ExampleRecursiveMapStringInterface() { buf := &bytes.Buffer{} enc := msgpack.NewEncoder(buf) in := map[string]interface{}{"foo": map[string]interface{}{"hello": "world"}} _ = enc.Encode(in) dec := msgpack.NewDecoder(buf) dec.DecodeMapFunc = func(d *msgpack.Decoder) (interface{}, error) { n, err := d.DecodeMapLen() if err != nil { return nil, err } m := make(map[string]interface{}, n) for i := 0; i < n; i++ { mk, err := d.DecodeString() if err != nil { return nil, err } mv, err := d.DecodeInterface() if err != nil { return nil, err } m[mk] = mv } return m, nil } out, err := dec.DecodeInterface() fmt.Printf("%v %#v\n", err, out) // Output: <nil> map[string]interface {}{"foo":map[string]interface {}{"hello":"world"}}}
在網路流中:
buf := &bytes.Buffer{}buf.Write([]byte{164, 97, 98, 99, 100})buf.Write([]byte{164, 97, 98, 99, 100})dec := msgpack.NewDecoder(buf)for { out, err := dec.DecodeBytes() if err != nil { break } fmt.Printf("%v %#v\n", err, string(out))}
json
-->loads:
①把json串解析到結構體
//-----------------json loads----------------// 把json串解析到結構體package mainimport ( "fmt" "encoding/json")func main(){ type carinfo struct { Id string License string Color int Device string // "<裝置類型>.<裝置id>" } type carlist struct { Result int Message string Cars []carinfo } var msg carlist json_str := `{"result":0, "message":"ok", "cars":[{"id":"311111", "license":"豫A1111", "color":2, "device":"VA3K.10001"}, {"id":"311112", "license":"豫A1112", "color":2, "device":"VA3K.10002"}]}` err := json.Unmarshal([]byte(json_str), &msg) if err != nil { fmt.Println("json loads err:", err) } fmt.Println(msg)}# {0 ok [{豫311111 A1111 2 VA3K.10001} {311112 豫A1112 2 VA3K.10002}]}
**結構體首字母要大寫, 並且和json串要對應
②把json串解析到interface
func main(){json_str := `{"result":0, "message":"ok", "cars":[{"id":"豫311111", "license":"A1111", "color":2, "device":"VA3K.10001"}, {"id":"311112", "license":"豫A1112", "color":2, "device":"VA3K.10002"}]}`var msg map[string]interface{}err := json.Unmarshal([]byte(json_str), &msg)if err == nil{fmt.Println(msg)}}# map[result:0 message:ok cars:[map[id:豫311111 license:A1111 color:2 device:VA3K.10001] map[id:311112 license:豫A1112 color:2 device:VA3K.10002]]]
-->dumps:
①
直接
b := []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`)
這樣就行了, 就可以用Unmarshal解析了
②使用Marshal
type Message struct { Name string Body string Time int64}m := Message{"Alice", "Hello", 1294706395881547000}b, err := json.Marshal(m)# b --> []byte(`{"Name":"Alice","Body":"Hello","Time":1294706395881547000}`)