源文件为jsonmarshal_test.go
package pmarshal
import (
"encoding/json"
"fmt"
"testing"
)
type Stu struct {
Name string `json:"jsonname"`
Age int
High bool
Sex string
Class *Class `json:"jsonclass"`
}
type Class struct {
Name string
Grade int
}
func TestMarshal(t *testing.T) {
stu := Stu{
Name: "Stu",
Age: 12,
Sex: "boy",
High: true,
}
cla := new(Class)
cla.Name = "c1"
cla.Grade = 5
stu.Class = cla
jstu, err := json.Marshal(stu)
if err != nil {
fmt.Println(err.Error())
return
}
fmt.Println(string(jstu))
}
func TestUnMarshal(t *testing.T) {
stu := Stu{
Name: "Stu",
Age: 12,
Sex: "boy",
High: true,
}
cla := new(Class)
stu.Class = cla
// here
cla.Name = "c1"
cla.Grade = 5
jstu, err := json.Marshal(stu)
if err != nil {
fmt.Println(err.Error())
return
}
t.Log(jstu)
//fmt.Println(string(jstu))
var s Stu
if err := json.Unmarshal(jstu, &s); err != nil {
t.Log(err.Error())
return
}
t.Log(s.Name)
t.Log(s.Age)
t.Log(s.Sex)
t.Log(s.High)
t.Log(s.Class.Grade)
t.Log(s.Class.Name)
}
json格式别名和结构体别名区别;
vscode下输出结果为:
Running tool: /usr/local/go/bin/go test -timeout 30s -run ^TestMarshal$ grpcTest/pmarshal
=== RUN TestMarshal
{"jsonname":"Stu","Age":12,"High":true,"Sex":"boy","jsonclass":{"Name":"c1","Grade":5}}
--- PASS: TestMarshal (0.00s)
PASS
ok grpcTest/pmarshal 0.016s
> 测试运行完成时间: 3/31/2022, 4:53:59 PM <
Running tool: /usr/local/go/bin/go test -timeout 30s -run ^TestUnMarshal$ grpcTest/pmarshal
=== RUN TestUnMarshal
/home/book/pt1416/02-hellogolang/grpcTest/pmarshal/jsonmarshal_test.go:87: [123 34 106 115 111 110 110 97 109 101 34 58 34 83 116 117 34 44 34 65 103 101 34 58 49 50 44 34 72 105 103 104 34 58 116 114 117 101 44 34 83 101 120 34 58 34 98 111 121 34 44 34 106 115 111 110 99 108 97 115 115 34 58 123 34 78 97 109 101 34 58 34 99 49 34 44 34 71 114 97 100 101 34 58 53 125 125]
/home/book/pt1416/02-hellogolang/grpcTest/pmarshal/jsonmarshal_test.go:95: Stu
/home/book/pt1416/02-hellogolang/grpcTest/pmarshal/jsonmarshal_test.go:96: 12
/home/book/pt1416/02-hellogolang/grpcTest/pmarshal/jsonmarshal_test.go:97: boy
/home/book/pt1416/02-hellogolang/grpcTest/pmarshal/jsonmarshal_test.go:98: true
/home/book/pt1416/02-hellogolang/grpcTest/pmarshal/jsonmarshal_test.go:99: 5
/home/book/pt1416/02-hellogolang/grpcTest/pmarshal/jsonmarshal_test.go:100: c1
--- PASS: TestUnMarshal (0.00s)
PASS
ok grpcTest/pmarshal (cached)
> 测试运行完成时间: 3/31/2022, 4:54:04 PM <