json.go 841 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
  1. package schema
  2. import (
  3. "bytes"
  4. "database/sql/driver"
  5. "errors"
  6. )
  7. type JSON []byte
  8. func (j JSON) Value() (driver.Value, error) {
  9. if j.IsNull() {
  10. return nil, nil
  11. }
  12. return string(j), nil
  13. }
  14. func (j *JSON) Scan(value interface{}) error {
  15. if value == nil {
  16. *j = nil
  17. return nil
  18. }
  19. s, ok := value.([]byte)
  20. if !ok {
  21. return errors.New("Invalid Scan Source")
  22. }
  23. *j = append((*j)[0:0], s...)
  24. return nil
  25. }
  26. func (m JSON) MarshalJSON() ([]byte, error) {
  27. if m == nil {
  28. return []byte("null"), nil
  29. }
  30. return m, nil
  31. }
  32. func (m *JSON) UnmarshalJSON(data []byte) error {
  33. if m == nil {
  34. return errors.New("null point exception")
  35. }
  36. *m = append((*m)[0:0], data...)
  37. return nil
  38. }
  39. func (j JSON) IsNull() bool {
  40. return len(j) == 0 || string(j) == "null"
  41. }
  42. func (j JSON) Equals(j1 JSON) bool {
  43. return bytes.Equal([]byte(j), []byte(j1))
  44. }