通过Marshaler和Unmarshaler接口,可以自定义序列化和反序列化时需要执行的操作。

  1. // #encoding/json/encode.go
  2. // Marshaler is the interface implemented by types that
  3. // can marshal themselves into valid JSON.
  4. type Marshaler interface {
  5. MarshalJSON() ([]byte, error)
  6. }
  7. // #encoding/json/decode.go
  8. // Unmarshaler is the interface implemented by types
  9. // that can unmarshal a JSON description of themselves.
  10. // The input can be assumed to be a valid encoding of
  11. // a JSON value. UnmarshalJSON must copy the JSON data
  12. // if it wishes to retain the data after returning.
  13. //
  14. // By convention, to approximate the behavior of Unmarshal itself,
  15. // Unmarshalers implement UnmarshalJSON([]byte("null")) as a no-op.
  16. type Unmarshaler interface {
  17. UnmarshalJSON([]byte) error
  18. }

TextMarshaler与Marshaler类似,优先级比Marshaler低。返回的是文本内容,不需要自己添加双引号。

  1. // #encoding/encoding.go
  2. // TextMarshaler is the interface implemented by an object that can
  3. // marshal itself into a textual form.
  4. //
  5. // MarshalText encodes the receiver into UTF-8-encoded text and returns the result.
  6. type TextMarshaler interface {
  7. MarshalText() (text []byte, err error)
  8. }
  9. // TextUnmarshaler is the interface implemented by an object that can
  10. // unmarshal a textual representation of itself.
  11. //
  12. // UnmarshalText must be able to decode the form generated by MarshalText.
  13. // UnmarshalText must copy the text if it wishes to retain the text
  14. // after returning.
  15. type TextUnmarshaler interface {
  16. UnmarshalText(text []byte) error
  17. }

BinaryMarshaler 是由一个对象实现的接口,它可以将自己编组为二进制形式。
MarshalBinary 将接收器编码为二进制形式并返回结果。

  1. // #encoding/encoding.go
  2. // BinaryMarshaler is the interface implemented by an object that can
  3. // marshal itself into a binary form.
  4. //
  5. // MarshalBinary encodes the receiver into a binary form and returns the result.
  6. type BinaryMarshaler interface {
  7. MarshalBinary() (data []byte, err error)
  8. }
  9. // BinaryUnmarshaler is the interface implemented by an object that can
  10. // unmarshal a binary representation of itself.
  11. //
  12. // UnmarshalBinary must be able to decode the form generated by MarshalBinary.
  13. // UnmarshalBinary must copy the data if it wishes to retain the data
  14. // after returning.
  15. type BinaryUnmarshaler interface {
  16. UnmarshalBinary(data []byte) error
  17. }

参考:

Golang JSON

golang json编码

Go语言中关于JSON的整理

编码 | encoding