json.go 694 B

123456789101112131415161718192021222324252627282930
  1. // Copyright 2014 Google Inc. All rights reserved.
  2. // Use of this source code is governed by a BSD-style
  3. // license that can be found in the LICENSE file.
  4. package uuid
  5. import "errors"
  6. func (u UUID) MarshalJSON() ([]byte, error) {
  7. if len(u) == 0 {
  8. return []byte(`""`), nil
  9. }
  10. return []byte(`"` + u.String() + `"`), nil
  11. }
  12. func (u *UUID) UnmarshalJSON(data []byte) error {
  13. if len(data) == 0 || string(data) == `""` {
  14. return nil
  15. }
  16. if len(data) < 2 || data[0] != '"' || data[len(data)-1] != '"' {
  17. return errors.New("invalid UUID format")
  18. }
  19. data = data[1 : len(data)-1]
  20. uu := Parse(string(data))
  21. if uu == nil {
  22. return errors.New("invalid UUID format")
  23. }
  24. *u = uu
  25. return nil
  26. }