golang -- 序列化 msgpack & json

flyking · · 6370 次点击 · · 开始浏览    
这是一个创建于 的文章,其中的信息可能已经有所发展或是发生改变。

下面总结一下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}`)






欢迎关注我们的微信公众号,每天学习Go知识

本文来自:开源中国博客

感谢作者:flyking

查看原文:golang -- 序列化 msgpack & json

入群交流(和以上内容无关):加入Go大咖交流群,或添加微信:liuxiaoyan-s 备注:入群;或加QQ群:731990104

6370 次点击  
加入收藏 微博
暂无回复
添加一条新回复 (您需要 登录 后才能回复 没有账号 ?)
  • 请尽量让自己的回复能够对别人有帮助
  • 支持 Markdown 格式, **粗体**、~~删除线~~、`单行代码`
  • 支持 @ 本站用户;支持表情(输入 : 提示),见 Emoji cheat sheet
  • 图片支持拖拽、截图粘贴等方式上传