基本类型数据转json字符串
bolB, _ := json.Marshal(true)
fmt.Println("bool json:", string(bolB))
bool json: true
intB, _ := json.Marshal(1)
fmt.Println("int json:", string(intB))
int json: 1
fltB, _ := json.Marshal(2.34)
fmt.Println("float json:", string(fltB))
float json: 2.34
strB, _ := json.Marshal("gopher")
fmt.Println("string json:", string(strB))
string json: “gopher”
集合类型数据转json字符串
slcD := []string{"apple", "peach", "pear"}
slcB, _ := json.Marshal(slcD)
fmt.Println("slice json:", string(slcB))
slice json: [“apple”,“peach”,“pear”]
mapD := map[string]int{"apple": 5, "lettuce": 7}
mapB, _ := json.Marshal(mapD)
fmt.Println("map json:", string(mapB))
map json: {“apple”:5,“lettuce”:7}
结构体类型数据转json字符串
type UJsonModel struct {
Page int
Fruits []string
}
type LJsonModel struct {
Page int `json:"page"`
Fruits []string `json:"fruits"`
}
uMdlD := &UJsonModel{
Page: 1,
Fruits: []string{
"apple",
"peach",
"pear",
},
}
uMdlB, _ := json.Marshal(uMdlD)
fmt.Println("upper model json:", string(uMdlB))
upper model json: {“Page”:1,“Fruits”:[“apple”,“peach”,“pear”]}
lMdlD := &LJsonModel{
Page: 1,
Fruits: []string{
"apple",
"peach",
"pear",
},
}
lMdlB, _ := json.Marshal(lMdlD)
fmt.Println("lower model json:", string(lMdlB))
lower model json: {“page”:1,“fruits”:[“apple”,“peach”,“pear”]}
结构体中,只有大写字母开头的字段才会在json中编码和解码。结构体的字段可使用标签进行json键名的自定义。
json字符串转集合类型数据
byt := []byte(`{"num":6.13,"strs":["a","b"]}`)
var dat map[string]interface{}
if err := json.Unmarshal(byt, &dat); err != nil {
panic(err)
}
fmt.Println(dat)
num := dat["num"].(float64)
fmt.Println("num:", num)
strs := dat["strs"].([]interface{})
str1 := strs[0].(string)
fmt.Println("strs[0]", str1)
map[num:6.13 strs:[a b]]
num: 6.13
strs[0] a
json字符串转结构体类型数据
str := `{"page":1,"fruits":["apple","peach"]}`
mdl := LJsonModel{}
json.Unmarshal([]byte(str), &mdl)
fmt.Println(mdl)
fmt.Println(mdl.Fruits[0])
{1 [apple peach]}
apple
json编码流式传输
enc := json.NewEncoder(os.Stdout)
d := map[string]int{"apple": 5, "lettuce": 7}
enc.Encode(d)
{“apple”:5,“lettuce”:7}