一.结构体转json,使用json.Marshal()
返回值([]byte, error)
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
Name string
Age int
Gender byte
Subject []string
}
func main() {
s := Student{
"XiaoMing",
15,
'M',
[]string{"数学","语文","英语"},
}
sJson,err := json.Marshal(s)
if err!=nil{
fmt.Println(err)
return
}
fmt.Println("json of s = ",string(sJson))
}
运行结果:
json of s = {"Name":"XiaoMing","Age":15,"Gender":77,"Subject":["数学","语文","英语"]}
二.json转结构体,使用json.Unmarshal([]byte(string),*s)
package main
import (
"encoding/json"
"fmt"
)
type Student struct {
Name string //“-”字段转换成json时舍弃
Age int
Gender byte
Subject []string
}
func main() {
str := `{
"name":"李雷",
"age": "15",
"gender": 77,
"subject": [
"数学",
"语文",
"英语"
]
}`
s:= new(Student)
json.Unmarshal([]byte(str),s)//第二个参数必须是指针
fmt.Println(*s)
}
运行结果:
{李雷 0 77 [数学 语文 英语]}
三.map转json
package main
import (
"encoding/json"
"fmt"
)
func main() {
m := make(map[string]interface{})
m["name"] = "HanMeimei"
m["age"] = 11
m["gender"] = 'M'
m["subject"] = []string{"语文","数学","英语"}
fmt.Println("m = ",m)
mJson,err := json.Marshal(m)
if err!=nil {
fmt.Println(err)
return
}
fmt.Printf("mJson = %s",mJson)
}
运行结果:
m = map[age:11 gender:77 name:HanMeimei subject:[语文 数学 英语]]
mJson = {"age":11,"gender":77,"name":"HanMeimei","subject":["语文","数学","英语"]}
四.json转map,数字默认为float64
package main
import (
"encoding/json"
"fmt"
)
func main() {
mJson := `{"age":11,"gender":77,"name":"HanMeimei","subject":["语文","数学","英语"]}`
m:=make(map[string]interface{})
json.Unmarshal([]byte(mJson),&m)
fmt.Println(m)
//类型断言
for key,value := range m{
switch value.(type){
case string:
fmt.Printf("m[%s] = %s,type = string\n",key,value)
case int:
fmt.Printf("m[%s] = %d,type = int\n",key,value)
case float64:
fmt.Printf("m[%s] = %f,type = float64\n",key,value)
case []interface{}:
fmt.Printf("m[%s] = %s,type = []interface{}\n",key,value)
case byte:
fmt.Printf("m[%s] = %s,type = byte\n",key,value)
}
}
}
运行结果:
map[age:11 gender:77 name:HanMeimei subject:[语文 数学 英语]]
m[name] = HanMeimei,type = string
m[subject] = [语文 数学 英语],type = []interface{}
m[age] = 11.000000,type = float64
m[gender] = 77.000000,type = float64