解析JSON
- 结构体中的小写字段非导出,不会被encode或decode
- 如果输入是字符串流,使用
json.Decoder
- 例如从一个HTTP response读取
- 如果数据已经在内存中,使用
json.Unmarshal
Unmarshal
func Unmarshal(data []byte, v interface{
}) error
// 使用
err := json.Unmarshal([]byte(s), &m)
v
是一个结构体指针或map指针- 能够被赋值的字段必须是可导出字段(即首字母大写)
- 当你接收到一个很大的JSON数据结构而你却只想获取其中的部分数据的时候,你只需将你想要的数据对应的字段名大写
- 如果不知道JSON数据的结构,可以先解析到空接口中,然后利用断言解析
Decoder
// NewDecoder returns a new decoder that reads from r.
func NewDecoder(r io.Reader) *Decoder
// Decode reads JSON-encoded value from input and stores it in the value pointed to by v.
func (dec *Decoder) Decode(