go语言中json的反序列化也是使用"encoding/json" 包。
示例如下:
type Student struct {
Name string `json:"stu_name"`
Age int `json:"stu_age"`
}
func main() {
str := `{"stu_name":"张三","stu_age":15}`
var stu Student
// 反序列化json,传递引用。
error:=json.Unmarshal([]byte(str),&stu)
if error != nil{
fmt.Println("json反序列化错误。。")
return
}
// {张三 15}
fmt.Println(stu)
}
说明:
1、需要保证json字符串的数据类型 和 结构体的数据类型一致。否则反序列化错误。
比如:
{"stu_name":"张三","stu_age":abc}
因为stu_age在结构体中是int,所以反序列化会报错。2、如果json字符串中不存在结构体对应的属性,反序列化后会设置为零值。
比如:
{"stu_name":"张三"}
反序列化之后,age会被设置为03、如果结构体带有tag,json字符串的key要匹配tag中的名字。否则序列化后找不到值,全部设置为零值。
比如:
{"Name":"张三","Age":15}
反序列化之后。Student 会设置为零值,最终得到{ 0}
4、tag必须是 `json:"名字"` 的格式。如果乱写。tag将被json包忽略,还是以字段名做json序列化和反序列化的key。
5、在反序列化为map、切片等引用类型时,不需要在外部使用make分配空间。json.Unmarshal 函数会在内部创建空间。
示例:tag乱写的情况。
tag乱写时,tag将被json包忽略,还是以字段名做json序列化和反序列化的key。tag还有其他写法,具体查看json包的文档。
type Student struct {
Name string `jso`
Age int `json:"stu_age"`
}
// 序列化函数
func Serialize() {
stu := Student{
Name:"张三",
Age:23,
}
stuJsonBytes, err := json.Marshal(&stu)
if err != nil{
fmt.Println("序列化错误。。")
return
}
// 序列化结果。。 {"Name":"张三","stu_age":23}
fmt.Println("序列化结果。。",string(stuJsonBytes))
}
// 反序列化函数
func Deserialize() {
str := `{"Name":"张三","stu_age":23}`
var stu2 Student
// 反序列化json
error:=json.Unmarshal([]byte(str),&stu2)
if error != nil{
fmt.Println("json反序列化错误。。")
return
}
// 反序列化结果。。。 {张三 23}
fmt.Println("反序列化结果。。。",stu2)
}
func main() {
Serialize()
Deserialize()
}