golang -- 序列化 msgpack & json

來源:互聯網
上載者:User
這是一個建立於 的文章,其中的資訊可能已經有所發展或是發生改變。

下面總結一下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}`)





相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.