下面总结一下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 main import ( "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}`)
有疑问加站长微信联系(非本文作者)