目录
一、概括
JSON(JavaScript Object Notation)web
gojson
json
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
Name string `json:"name"` // 姓名
Age int `json:"age"` // 年龄
Gender string `json:"gender"` // 性别
Score float64 `json:"score"` // 分数
Course []string `json:"course"` // 课程
}
func main() {
stu := Student{
"张三",
20,
"男",
78.6,
[]string{"语文", "数学", "音乐"},
}
fmt.Println(stu)
data, err := json.Marshal(&stu)
if err != nil {
fmt.Println("序列化错误", err)
} else {
fmt.Println(string(data))
}
}
// 返回结果:{"name":"张三","age":20,"gender":"男","score":78.6,"course":["语文","数学","音乐"]}
复制代码
mapjson
package main
import (
"encoding/json"
"fmt"
)
func main() {
var map1 map[string]interface{} // 使用一个空接口表示可以是任意类型
map1 = make(map[string]interface{})
map1["name"] = "张三"
map1["province"] = "广东省"
map1["city"] = "深圳市"
map1["salary"] = 1000
map1["hobby"] = [...]string{"看书", "旅游", "学习"}
data, err := json.Marshal(map1)
if err != nil {
fmt.Println("序列化失败")
} else {
fmt.Println(string(data))
}
}
复制代码
json
package main
import (
"encoding/json"
"fmt"
)
func main() {
var slice1 []map[string]interface{}
var m1 map[string]interface{}
m1 = make(map[string]interface{})
m1["name"] = "张三"
m1["address"] = "广东省深圳市"
slice1 = append(slice1, m1)
var m2 map[string]interface{}
m2 = make(map[string]interface{})
m2["name"] = "李四"
m2["address"] = "广东省广州市"
slice1 = append(slice1, m2)
data, err := json.Marshal(slice1)
if err != nil {
fmt.Println("序列化错误")
} else {
fmt.Println(string(data))
}
}
复制代码
jsongomap
json
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
Name string `json:"name"` // 姓名
Age int `json:"age"` // 年龄
Gender string `json:"gender"` // 性别
Score float64 `json:"score"` // 分数
Course []string `json:"course"` // 课程
}
func main() {
var stu Student
str := `{"name":"张三","age":20,"gender":"男","score":78.6,"course":["语文","数学","音乐"]}`
err := json.Unmarshal([]byte(str), &stu)
if err != nil {
fmt.Println("反序列化失败")
}
fmt.Println(stu)
}
复制代码
jsonmap
package main
import (
"encoding/json"
"fmt"
)
func main() {
var map1 map[string]interface{} // 使用一个空接口表示可以是任意类型
//map1 = make(map[string]interface{})
str := `{"city":"深圳市","hobby":["看书","旅游","学习"],"name":"张三","province":"广东省","salary":1000}`
err := json.Unmarshal([]byte(str), &map1)
if err != nil {
fmt.Println("反序列化失败", err)
}
fmt.Println(map1)
}
复制代码
3、切片反序列化
package main
import (
"encoding/json"
"fmt"
)
func main() {
var slice []map[string]interface{}
str := `[{"address":"广东省深圳市","name":"张三"},{"address":"广东省广州市","name":"李四"}]`
err := json.Unmarshal([]byte(str), &slice)
if err != nil {
fmt.Printf("unmarshal err=%v\n", err) }
fmt.Printf("反序列化后 slice=%v\n", slice)
}
复制代码