ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
Go语言中的json包在序列化空接口存放的数字类型(整型、浮点型等)都序列化成float64类型。 ~~~ func jsonDemo() { var s1 = s{ data: make(map[string]interface{}, 8), } s1.data["count"] = 1 ret, 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("marshal 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 ~~~ gob序列化 ~~~ // gob序列化 func gobDemo() { var s1 = s{ data: make(map[string]interface{}, 8), } s1.data["count"] = 1 // encode buf := 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), } // decode dec := gob.NewDecoder(bytes.NewBuffer(b)) err = dec.Decode(&s2.data) if err != nil { fmt.Println("gob encode failed, err: ", err) return } fmt.Println(s2.data) for _, v := range s2.data { fmt.Printf("value:%v, type:%T\n", v, v) } } ~~~ msgpack序列化 ~~~ func main() { p1 := Person{ Name: "alice", Age: 18, Gender: "男", } // marshal b, err := msgpack.Marshal(p1) if err != nil { fmt.Printf("msgpack marshal failed, err:%v", err) return } // unmarshal var p2 Person err = 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:"alice", Age:18, Gender:"男"} ~~~