golang之marshal处理json格式

源文件为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 <
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值