本文主要是介绍json序列化 (gob标准库),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
json序列化 (gob标准库)
type s struct {data map[string]interface{}
}
1.json序列化
会将 int 类型,转化成float64。
func jsonDemo() {var s1 = s{data: make(map[string]interface{}, 8),}s1.data["count"] = 1ret, err := json.Marshal(s1.data)if err != nil {fmt.Println("marshal failed", err)}fmt.Printf("%#v\n", string(ret))var s2 = s{data: make(map[string]interface{}, 8),}err = json.Unmarshal(ret, &s2.data)if err != nil {fmt.Println("unmarshal failed", err)}fmt.Println(s2)for _, v := range s2.data {fmt.Printf("value:%v, type:%T\n", v, v)}
}输出结果:
"{\"count\":1}"
{map[count:1]}
value:1, type:float64
2.gob序列化:
标准库gob是golang提供的“私有”的编解码方式,它的效率会比json,xml等更高,特别适合在Go语言程序间传递数据。
func gobDemo() {var s1 = s{data: make(map[string]interface{}, 8),}s1.data["count"] = 1// encodebuf := new(bytes.Buffer)enc := gob.NewEncoder(buf)err := enc.Encode(s1.data)if err != nil {fmt.Println("gob encode failed, err:", err)return}b := buf.Bytes()fmt.Println(b)var s2 = s{data: make(map[string]interface{}, 8),}// decodedec := gob.NewDecoder(bytes.NewBuffer(b))err = dec.Decode(&s2.data)if err != nil {fmt.Println("gob decode failed, err", err)return}fmt.Println(s2.data)for _, v := range s2.data {fmt.Printf("value:%v, type:%T\n", v, v)}
}
3.msgpack:
MessagePack是一种高效的二进制序列化格式。它允许你在多种语言(如JSON)之间交换数据。但它更快更小。
go get -u github.com/vmihailenco/msgpack
package mainimport ("fmt""github.com/vmihailenco/msgpack"
)// msgpack demotype Person struct {Name stringAge intGender string
}func main() {p1 := Person{Name: "沙河娜扎",Age: 18,Gender: "男",}// marshalb, err := msgpack.Marshal(p1)if err != nil {fmt.Printf("msgpack marshal failed,err:%v", err)return}// unmarshalvar p2 Personerr = msgpack.Unmarshal(b, &p2)if err != nil {fmt.Printf("msgpack unmarshal failed,err:%v", err)return}fmt.Printf("p2:%#v\n", p2) // p2:main.Person{Name:"沙河娜扎", Age:18, Gender:"男"}
}
这篇关于json序列化 (gob标准库)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!