json_enc.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. // Copyright 2012-2018 The NATS Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. package builtin
  14. import (
  15. "encoding/json"
  16. "strings"
  17. )
  18. // JsonEncoder is a JSON Encoder implementation for EncodedConn.
  19. // This encoder will use the builtin encoding/json to Marshal
  20. // and Unmarshal most types, including structs.
  21. type JsonEncoder struct {
  22. // Empty
  23. }
  24. // Encode
  25. func (je *JsonEncoder) Encode(subject string, v interface{}) ([]byte, error) {
  26. b, err := json.Marshal(v)
  27. if err != nil {
  28. return nil, err
  29. }
  30. return b, nil
  31. }
  32. // Decode
  33. func (je *JsonEncoder) Decode(subject string, data []byte, vPtr interface{}) (err error) {
  34. switch arg := vPtr.(type) {
  35. case *string:
  36. // If they want a string and it is a JSON string, strip quotes
  37. // This allows someone to send a struct but receive as a plain string
  38. // This cast should be efficient for Go 1.3 and beyond.
  39. str := string(data)
  40. if strings.HasPrefix(str, `"`) && strings.HasSuffix(str, `"`) {
  41. *arg = str[1 : len(str)-1]
  42. } else {
  43. *arg = str
  44. }
  45. case *[]byte:
  46. *arg = data
  47. default:
  48. err = json.Unmarshal(data, arg)
  49. }
  50. return
  51. }