raw.go 1.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package easyjson
  2. import (
  3. "github.com/mailru/easyjson/jlexer"
  4. "github.com/mailru/easyjson/jwriter"
  5. )
  6. // RawMessage is a raw piece of JSON (number, string, bool, object, array or
  7. // null) that is extracted without parsing and output as is during marshaling.
  8. type RawMessage []byte
  9. // MarshalEasyJSON does JSON marshaling using easyjson interface.
  10. func (v *RawMessage) MarshalEasyJSON(w *jwriter.Writer) {
  11. if len(*v) == 0 {
  12. w.RawString("null")
  13. } else {
  14. w.Raw(*v, nil)
  15. }
  16. }
  17. // UnmarshalEasyJSON does JSON unmarshaling using easyjson interface.
  18. func (v *RawMessage) UnmarshalEasyJSON(l *jlexer.Lexer) {
  19. *v = RawMessage(l.Raw())
  20. }
  21. // UnmarshalJSON implements encoding/json.Unmarshaler interface.
  22. func (v *RawMessage) UnmarshalJSON(data []byte) error {
  23. *v = data
  24. return nil
  25. }
  26. var nullBytes = []byte("null")
  27. // MarshalJSON implements encoding/json.Marshaler interface.
  28. func (v RawMessage) MarshalJSON() ([]byte, error) {
  29. if len(v) == 0 {
  30. return nullBytes, nil
  31. }
  32. return v, nil
  33. }
  34. // IsDefined is required for integration with omitempty easyjson logic.
  35. func (v *RawMessage) IsDefined() bool {
  36. return len(*v) > 0
  37. }