type header struct {
Encryption string json:"encryption"
Timestamp int64 json:"timestamp"
Key string json:"key"
Partnercode int json:"partnercode"
}
//转换成JSON字符串
headerO1 := header{
Encryption: "sha",
Timestamp: 1482463793,
Key: "2342874840784a81d4d9e335aaf76260",
Partnercode: 10025,
}
jsons, errs := json.Marshal(headerO1) //转换成JSON返回的是byte[]
if errs != nil {
fmt.Println(errs.Error())
}
fmt.Println(string(jsons)) //byte[]转换成string 输出
//输出:{"encryption":"sha","timestamp":1482463793,"key":"2342874840784a81d4d9e335aaf76260","partnercode":10025}
//解析JSON成结构体(1)
var headers string = {"encryption":"md5","timestamp":1482463793,"key":"2342874840784a81d4d9e335aaf76260","partnercode":100034}
headerObj := header{}
json.Unmarshal([]byte(headers), &headerObj)//json解析到结构体里面
fmt.Println(headerObj) //输入结构体
//输出 {sha 1482463793 2342874840784a81d4d9e335aaf76260 10025}
//解析JSON成结构体(2)指定解析的长度
headerReader := io.LimitReader(strings.NewReader(headers), 1024)
headerObj3 := header{}
errs := json.NewDecoder(headerReader).Decode(&headerObj3)
if errs != nil {
fmt.Println(errs.Error())
}
作者:若尘拂风
来源:CSDN
原文:https://blog.csdn.net/shachao888/article/details/53840577
版权声明:本文为博主原创文章,转载请附上博文链接!
有疑问加站长微信联系(非本文作者)