marshal与unmarshal是一对序列化的逆过程。
json中的marshal与unmarshal
在go的json解析中,可以使用marshal与unmarshal做数据的json编码与解码。 json格式的数据虽然易读性较好,但是在序列化后体积比较大,影响并发,并且序列化的性能低。 在go中使用json的,需要导入encoding/json的依赖包,通过json.Marshal和json.Unmarshal方法实现序列化与反序列化。 反序列化需要指定对象。
type A struct{
Id int64 'json:"id.string, omitempty"'
Name string 'json:"-"'
}
func main(){
var a A = &A{Id:38822}
data, _ := json.Marshal(a)
var b A
json.Unmarshal(data, &b)
}
MsgPack中的marshal与unmarshal
这是json的二进制版本,空间占用晓,序列化和反序列化的性能高 导入github.com/vmihailenco/msgpack的依赖,调用msgpack.Marshal和msgpack.Unmarshal进行序列化和反序列化
protobuf中的marshal与unmarshal
protobuf是谷歌推出的 在go的proto中,可以使用marshal与unmarshal做序列化和反序列化。它具有灵活、高效、自动化的特点,基于IDL(接口描述语言)的自动化代码生成。 在protobuf的开发中,使用IDL编写,以生成指定语言的代码进行序列化和反序列化。 使用proto.Marshal和proto.Unmarshal做序列化和反序列化