marshal_json.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445
  1. package runtime
  2. import (
  3. "encoding/json"
  4. "io"
  5. )
  6. // JSONBuiltin is a Marshaler which marshals/unmarshals into/from JSON
  7. // with the standard "encoding/json" package of Golang.
  8. // Although it is generally faster for simple proto messages than JSONPb,
  9. // it does not support advanced features of protobuf, e.g. map, oneof, ....
  10. //
  11. // The NewEncoder and NewDecoder types return *json.Encoder and
  12. // *json.Decoder respectively.
  13. type JSONBuiltin struct{}
  14. // ContentType always Returns "application/json".
  15. func (*JSONBuiltin) ContentType() string {
  16. return "application/json"
  17. }
  18. // Marshal marshals "v" into JSON
  19. func (j *JSONBuiltin) Marshal(v interface{}) ([]byte, error) {
  20. return json.Marshal(v)
  21. }
  22. // Unmarshal unmarshals JSON data into "v".
  23. func (j *JSONBuiltin) Unmarshal(data []byte, v interface{}) error {
  24. return json.Unmarshal(data, v)
  25. }
  26. // NewDecoder returns a Decoder which reads JSON stream from "r".
  27. func (j *JSONBuiltin) NewDecoder(r io.Reader) Decoder {
  28. return json.NewDecoder(r)
  29. }
  30. // NewEncoder returns an Encoder which writes JSON stream into "w".
  31. func (j *JSONBuiltin) NewEncoder(w io.Writer) Encoder {
  32. return json.NewEncoder(w)
  33. }
  34. // Delimiter for newline encoded JSON streams.
  35. func (j *JSONBuiltin) Delimiter() []byte {
  36. return []byte("\n")
  37. }