Json处理
1 序列化
// 结构体和JSON映射
type Conf struct {
Addr string `json:"addr,omitempty"`
Port string `json:"port"`
User string `json:"user"`
Password string `json:"password"`
}
func main() {
conf := Conf{
Addr: "1",
Port: "1",
User: "1",
Password: "1",
}
data, _ := json.Marshal(conf)
// 格式化json
data_dent, _ := json.MarshalIndent(conf, "", " ")
fmt.Println(string(data))
fmt.Println(string(data_dent))
}2 反序列化
3 流式处理
3.1 json.Decoder类型
3.1.1 json.NewDecoder(r io.Reader) *Decoder
3.1.2 (dec *Decoder) Buffered() io.Reader
3.1.3 (dec *Decoder) Decode(v any) error
3.1.4 (dec *Decoder) DisallowUnknownFields()
3.1.5 (dec *Decoder) InputOffset() int64
3.1.6 (dec *Decoder) More() bool
3.1.7 (dec *Decoder) Token() (Token, error)
3.1.8 (dec *Decoder) UseNumber()
3.2 json.Encoder类型
3.2.1 func NewEncoder(w io.Writer) *Encoder
3.2.2 func (enc *Encoder) Encode(v any) error
3.2.3 func (enc *Encoder) SetEscapeHTML(on bool)
3.2.4 func (enc *Encoder) SetIndent(prefix, indent string)
4 判断字节切片是否为有效JSON
5 结构体标签
标签选项
说明
6 分隔符
6.1 json.Delim类型
6.1.1 func (d Delim) String() string
7 特殊处理
7.1 json.Number 类型
7.1.1 func (n Number) Float64() (float64, error)
7.1.2 func (n Number) Int64() (int64, error)
7.1.3 func (n Number) String() string
7.2 使用场景:
7.2.1 json.RawMessage 类型
7.2.2 func (m RawMessage) MarshalJSON() ([]byte, error)
7.2.3 func (m *RawMessage) UnmarshalJSON(data []byte) error
8 使用场景:
9 json.Token 类型
10 自定义序列化/反序列化
10.1 json.Marshaler 接口
10.2 json.Unmarshaler 接口
11 接口反序列化
最后更新于