json.go 734 B

123456789101112131415161718192021222324252627
  1. // Package json_util provides JSON utilities including a custom RawMessage type.
  2. package json_util
  3. import (
  4. "errors"
  5. )
  6. // RawMessage is a custom JSON raw message type that marshals empty slices as "null".
  7. type RawMessage []byte
  8. // MarshalJSON customizes the JSON marshaling behavior for RawMessage.
  9. // Empty RawMessage values are marshaled as "null" instead of "[]".
  10. func (m RawMessage) MarshalJSON() ([]byte, error) {
  11. if len(m) == 0 {
  12. return []byte("null"), nil
  13. }
  14. return m, nil
  15. }
  16. // UnmarshalJSON sets *m to a copy of the JSON data.
  17. func (m *RawMessage) UnmarshalJSON(data []byte) error {
  18. if m == nil {
  19. return errors.New("json.RawMessage: UnmarshalJSON on nil pointer")
  20. }
  21. *m = append((*m)[0:0], data...)
  22. return nil
  23. }