编码为JSON格式
type header struct {
Encryption string `json:"encryption"`
Timestamp int64 `json:"timestamp"`
Key string `json:"key"`
Partnercode int `json:"partnercode"`
}
//初始化结构体
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}
解码为结构体
var headers string =`{"encryption":"md5","timestamp":1482463793,"key":"2342874840784a81d4d9e335aaf76260","partnercode":100034}`
headerObj := header{}
_ := json.Unmarshal([]byte(headers), &headerObj)
fmt.Println(headerObj)
//输入结构体 {sha 1482463793 2342874840784a81d4d9e335aaf76260 10025}
自定义结构体的JSON编码格式
package main
import (
"fmt"
"encoding/json"
"bytes"
)
type Device struct{
SN string `json:"s"`
Model string `json:"m,omitempty"`
}
func (d Device) String() string{
return fmt.Sprintf("serial:%s model:%s", d.SN, d.Model)
}
var m = map[string]interface{}{
"test":"<html>&<body>",
"sn": "123456",
"platform": 565,
"force": true,
"location": []string{"paris","beijing"},
"decr": ""
}
func encodeJson(v interface{}) ([]byte, error){
var buf bytes.Buffer
encoder := json.NewEncoder(&buf)
encoder.SetEscapeHTML(false)
if err := encoder.Encode(v); err != nil{
return nil, err
}
return buf.Bytes(), nil
}
func main() {
if s, err := json.Marshal(m); err != nil{
panic(err)
}else{
fmt.Println(string(s))
}
if b, err := encodeJson(m); err != nil{
panic(err)
}else{
fmt.Println(string(b))
}
d := Device{SN:"123456", Model:"http://baidu.com"}
if ds, err := encodeJson(d); err != nil{
panic(err)
}else{
fmt.Println(string(ds))}
}
输出:
{"decr":"","force":true,"location":["paris","beijing"],"platform":565,"sn":"123456","test":"\u003chtml\u003e\u0026\u003cbody\u003e"}
{"decr":"","force":true,"location":["paris","beijing"],"platform":565,"sn":"123456","test":"&"}
{"s":"123456","m":"http://baidu.com"}