映射和JSON数据格式类似,都是键值对,所以映射的序列化与反序列化都可以参考 JSON 。代码如下所示:
//序列化map
func TestSerializeMap(t *testing.T) {
oracle:=make(map[string]interface{})
oracle["Version"]="11.2.0.4"
oracle["IP"] ="192.168.0.200"
oracle["port"]=1521
//序列化转换成json
b,err := json.Marshal(oracle)
if err !=nil {
fmt.Println("marshal err: ",err.Error())
return
}
//将json字节数组转为成string输出
fmt.Println("marshal json:",string(b))
}
//输出:
marshal json: {"IP":"192.168.0.200","Version":"11.2.0.4","port":1521}
映射的反序列化
//反序列化map
func TestDeSerializeMap(t *testing.T) {
jsonStr := ` {"IP":"192.168.0.200","Version":"11.2.0.4","port":1521}`
oracle:=make(map[string]interface{})
//json反序列化转换成map
err := json.Unmarshal([]byte(jsonStr),&oracle)
if err !=nil {
fmt.Println("DeSerializeMap err: ",err.Error())
return
}
//输出类型和值
fmt.Printf("%T , %v",oracle,oracle)
}
//输出:
map[string]interface {} , map[IP:192.168.0.200 Version:11.2.0.4 port:1521]