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{}{
"sn": "123456",
"platform": 602,
"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))
}
}
网友评论