You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

25 lines
543 B

2 years ago
  1. package protobuf
  2. import (
  3. "github.com/golang/protobuf/jsonpb"
  4. "github.com/golang/protobuf/proto"
  5. )
  6. func ToJson(pb proto.Message) (string, error) {
  7. // 编码 protobuf 对象到 json
  8. m := &jsonpb.Marshaler{}
  9. m.OrigName = true // 使用 protobuf 定义的字段名称,而不是驼峰名称,便于识别
  10. jsData, err := m.MarshalToString(pb)
  11. if err != nil {
  12. return "", err
  13. }
  14. return jsData, nil
  15. }
  16. func ToPrtobuf(s string, p proto.Message) error {
  17. err := jsonpb.UnmarshalString(s, p)
  18. if err != nil {
  19. return err
  20. }
  21. return nil
  22. }