golang中直接导入“encoding/json”包即可使用json.
主要是json.Marshal与json.Unmarshal两个函数的使用。
func Marshal(v interface{}) ([]byte, error)
func Unmarshal(data []byte, v interface{}) error
这里示例代码及输出为:
package main
import (
"fmt"
"encoding/json"
)
type Student struct {
Name string
Age int64
Weight float64
Height float64
}
func main() {
s1 := Student{
Name: "jack",
Age: 20,
Weight: 71.5,
Height: 172.5,
}
b, err := json.Marshal(s1)
if err != nil {
fmt.Printf("json.Marshal failed, err:%v\n", err)
return
}
fmt.Printf("s1: %s\n", b)
var s2 Student
err = json.Unmarshal(b, &s2)
if err != nil {
fmt.Printf("json.Unmarshal failed, err:%v\n", err)
return
}
fmt.Printf("s2: %#v\n", s2)
}
输出:
s1: {"Name":"jack","Age":20,"Weight":71.5,"Height":172.5}
s2: main.Student{Name:"jack", Age:20, Weight:71.5, Height:172.5}
延用以上的代码,将普通结构体改为具名嵌套结构体:
type BodyInfo struct {
Weight float64
Height float64
}
type Student struct {
Name string
Age int64
BodyInfo BodyInfo
}
此时s1有不同的初始化方法:
初始化一:
s1 := Student{
Name: "jack",
Age: 20,
BodyInfo: BodyInfo{
Weight: 71.5,
Height: 172.5,
},
}
输出:
s1: {"Name":"jack","Age":20,"BodyInfo":{"Weight":71.5,"Height":172.5}}
s2: main.Student{Name:"jack", Age:20, BodyInfo:main.BodyInfo{Weight:71.5, Height:172.5}}
初始化二:
var s1 Student
s1.Name = "jack"
s1.Age = 20
s1.BodyInfo = BodyInfo {
Weight: 71.5,
Height: 172.5,
}
输出:
s1: {"Name":"jack","Age":20,"BodyInfo":{"Weight":71.5,"Height":172.5}}
s2: main.Student{Name:"jack", Age:20, BodyInfo:main.BodyInfo{Weight:71.5, Height:172.5}}
延用以上的代码,将普通结构体改为匿名嵌套结构体:
type BodyInfo struct {
Weight float64
Height float64
}
type Student struct {
Name string
Age int64
BodyInfo
}
此时s1有不同的初始化方法:
初始化一:
var s1 Student
s1.Name = "jack"
s1.Age = 20
s1.BodyInfo = BodyInfo {
Weight: 71.5,
Height: 172.5,
}
输出:
s1: {"Name":"jack","Age":20,"Weight":71.5,"Height":172.5}
s2: main.Student{Name:"jack", Age:20, BodyInfo:main.BodyInfo{Weight:71.5, Height:172.5}}
初始化二:
s1 := Student{
Name: "jack",
Age: 20,
BodyInfo: BodyInfo{
Weight: 71.5,
Height: 172.5,
},
}
输出:
str:{"Name":"jack","Age":20,"Weight":71.5,"Height":172.5}
s2:main.Student{Name:"jack", Age:20, BodyInfo:main.BodyInfo{Weight:71.5, Height:172.5}}
注:具名嵌套结构体与匿名嵌套结构体在序列化后存在是否摊平的差别。