golang 对象 struct 类型转json

时间:2025-02-26 07:30:07

通常json 中的key都是小写的,但是struct 中的成员不能是小写的,所以声明struct 如下:

 type header struct {
	Encryption  string `json:"encryption"`
	Timestamp   int64  `json:"timestamp"`
	Key         string `json:"key"`
	Partnercode int    `json:"partnercode"`
 }

转json:

//转换成JSON字符串
headerTest := header{
	Encryption:  "sha",
	Timestamp:   1482463793,
	Key:         "2342874840784a81d4d9e335aaf76260",
	Partnercode: 10025,
}
jsons, errs := (headerTest) //转换成JSON返回的是byte[]
if errs != nil {
   (())
}
(string(jsons)) //byte[]转换成string 输出