json.go 673 B

12345678910111213141516171819202122232425262728293031323334
  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) != 16 {
  8. return []byte(`""`), nil
  9. }
  10. var js [38]byte
  11. js[0] = '"'
  12. encodeHex(js[1:], u)
  13. js[37] = '"'
  14. return js[:], nil
  15. }
  16. func (u *UUID) UnmarshalJSON(data []byte) error {
  17. if string(data) == `""` {
  18. return nil
  19. }
  20. if data[0] != '"' {
  21. return errors.New("invalid UUID format")
  22. }
  23. data = data[1 : len(data)-1]
  24. uu := Parse(string(data))
  25. if uu == nil {
  26. return errors.New("invalid UUID format")
  27. }
  28. *u = uu
  29. return nil
  30. }