json.go 840 B

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. package common
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "github.com/golang/protobuf/jsonpb"
  6. "google.golang.org/protobuf/types/known/structpb"
  7. "github.com/gogo/protobuf/proto"
  8. )
  9. var jsonpbMarshaler *jsonpb.Marshaler
  10. func init() {
  11. jsonpbMarshaler = &jsonpb.Marshaler{
  12. EnumsAsInts: true,
  13. EmitDefaults: true,
  14. OrigName: true,
  15. }
  16. }
  17. func MarshalJSON(v interface{}) []byte {
  18. if _, ok := v.(proto.Message); ok {
  19. var buf bytes.Buffer
  20. err := jsonpbMarshaler.Marshal(&buf, v.(proto.Message))
  21. if err != nil {
  22. return nil
  23. }
  24. return buf.Bytes()
  25. }
  26. j, _ := json.Marshal(v)
  27. return j
  28. }
  29. func NewStructValuePB(v interface{}) *structpb.Value {
  30. s := new(structpb.Value)
  31. s.UnmarshalJSON(MarshalJSON(v))
  32. return s
  33. }
  34. func NewStructValuePBByBytes(v []byte) *structpb.Value {
  35. s := new(structpb.Value)
  36. s.UnmarshalJSON(v)
  37. return s
  38. }