GO语言的JSON02---反序列化
Posted xiaoqiang1_1
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了GO语言的JSON02---反序列化相关的知识,希望对你有一定的参考价值。
package main import ( "encoding/json" "fmt" ) type Human struct { Name string Age int Rmb float64 Gender bool Hobbies []string } var jsonStr = `{ "name":"梅川酷子", "age":40, "rmb":12345.123, "gender":false, "hobbies":["抽烟","喝酒","烫头"] }` var jsonStr2 = `[ { "name":"梅川酷子", "age":40, "rmb":12345.123, "gender":false, "hobbies":["抽烟","喝酒","烫头"] }, { "name":"朴成幸", "age":40, "rmb":12345.123, "gender":false, "hobbies":["抽烟","喝酒","烫头"] } ]` //将json反序列化为Map func main051() { retMap := make(map[string]interface{}) err := json.Unmarshal([]byte(jsonStr), &retMap) if err != nil{ fmt.Println("反序列化失败,err=",err) return } fmt.Println(retMap) } //将json数组反序列化为切片 func main052() { retSlice := make([]map[string]interface{},0) err := json.Unmarshal([]byte(jsonStr2), &retSlice) if err != nil{ fmt.Println("反序列化失败,err=",err) return } fmt.Println(retSlice) } /*将json对象反序列化为结构体*/ func main053() { human := new(Human) err := json.Unmarshal([]byte(jsonStr), human) if err != nil{ fmt.Println("反序列化失败,err=",err) return } fmt.Println(human) } /*将json数组反序列化为切片嵌套结构体*/ func main() { retSlice := make([]Human, 0) err := json.Unmarshal([]byte(jsonStr2), &retSlice) if err != nil{ fmt.Println("反序列化失败,err=",err) return } fmt.Println(retSlice) }
以上是关于GO语言的JSON02---反序列化的主要内容,如果未能解决你的问题,请参考以下文章
Go语言的JSON输入(解码)(反序列化)之struct存储