Go: Marshal、MarshalIndent、Unmarshal



MarshalIndent相比于Marhsal()的区别就在于读结果做了Indent 的处理: Indent 的代码有点长,简单说就是对Json 多了一些格式处理:



Json Marshal:将数据编码成json字符串


	m:= map[string]string{"one":"你好","two":"我是","three":"汪汪队"}
	
	//map转json Marshal
	v1,err1 :=json.Marshal(m)
	if err!=nil{
		fmt.Println(err1)			//错误信息
	}else{
		fmt.Println(string(v1))
	}
	输出结果为:{"one":"你好","three":"汪汪队","two":"我是"}





Json MarshalIndent:将数据编码成json字符串


	m:= map[string]string{"one":"你好","two":"我是","three":"汪汪队"}

	//map转json MarshalIndent

	v,err :=json.MarshalIndent(m,"","\t")
	if err!=nil{
		fmt.Println(err)			//错误信息
	}else{
		fmt.Println(string(v))
	}
	
	输出结果为:{
				"one": "你好",
				"three": "汪汪队",
				"two": "我是"
			   }




Json Unmarshal:将json字符串解码到相应的数据结构


	m:= map[string]string{"one":"你好","two":"我是","three":"汪汪队"}
	var w= map[string]string{}
	
	err2:=json.Unmarshal(v1,&w)
	if err2!=nil{
		fmt.Println(err2)
	}else{
		fmt.Println(w)
	}
	
	输出结果为:map[one:你好 three:汪汪队 two:我是]

你可能感兴趣的:(Go)