GO json的操作

##encoding/json标准库

Marshal 和 Unmarshal

编码:
func Marshal(v interface{}) ([]byte, error)
func NewEncoder(w io.Writer) *Encoder
[func (enc *Encoder) Encode(v interface{}) error
解码:
func Unmarshal(data []byte, v interface{}) error
func NewDecoder(r io.Reader) *Decoder
func (dec *Decoder) Decode(v interface{}) error

json类型仅支持string作为关键字,因而转义map时,map[int]T类型会报错(T为任意类型)
Channel, complex, and function types不能被转义
不支持循环类型的数据,因为这会导致Marshal死循环
指针会被转义为其所指向的值

MarshalIndent 函数(功能和 Marshal一致,只是格式化 json)

Encoder 和 Decoder

Request 之类的输入流中直接读取 json 进行解析或将编码的 json 直接输出,为了方便,标准库为我们提供了 Decoder 和 Encoder 类型。
它们分别通过一个 io.Reader 和 io.Writer 实例化,并从中读取数据或写数据。

1
2
3
输出JSON
jsonStr := []byte(`{"Name":"felix","Age":33}
json.NewEncoder(w).Encode(jsonStr);