json.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // Copyright 2015 The Go Authors. 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 jsonpb provides functionality to marshal and unmarshal between a
  5. // protocol buffer message and JSON. It follows the specification at
  6. // https://developers.google.com/protocol-buffers/docs/proto3#json.
  7. //
  8. // Do not rely on the default behavior of the standard encoding/json package
  9. // when called on generated message types as it does not operate correctly.
  10. //
  11. // Deprecated: Use the "google.golang.org/protobuf/encoding/protojson"
  12. // package instead.
  13. package jsonpb
  14. import (
  15. "github.com/golang/protobuf/proto"
  16. "google.golang.org/protobuf/reflect/protoreflect"
  17. "google.golang.org/protobuf/reflect/protoregistry"
  18. "google.golang.org/protobuf/runtime/protoimpl"
  19. )
  20. // AnyResolver takes a type URL, present in an Any message,
  21. // and resolves it into an instance of the associated message.
  22. type AnyResolver interface {
  23. Resolve(typeURL string) (proto.Message, error)
  24. }
  25. type anyResolver struct{ AnyResolver }
  26. func (r anyResolver) FindMessageByName(message protoreflect.FullName) (protoreflect.MessageType, error) {
  27. return r.FindMessageByURL(string(message))
  28. }
  29. func (r anyResolver) FindMessageByURL(url string) (protoreflect.MessageType, error) {
  30. m, err := r.Resolve(url)
  31. if err != nil {
  32. return nil, err
  33. }
  34. return protoimpl.X.MessageTypeOf(m), nil
  35. }
  36. func (r anyResolver) FindExtensionByName(field protoreflect.FullName) (protoreflect.ExtensionType, error) {
  37. return protoregistry.GlobalTypes.FindExtensionByName(field)
  38. }
  39. func (r anyResolver) FindExtensionByNumber(message protoreflect.FullName, field protoreflect.FieldNumber) (protoreflect.ExtensionType, error) {
  40. return protoregistry.GlobalTypes.FindExtensionByNumber(message, field)
  41. }
  42. func wellKnownType(s protoreflect.FullName) string {
  43. if s.Parent() == "google.protobuf" {
  44. switch s.Name() {
  45. case "Empty", "Any",
  46. "BoolValue", "BytesValue", "StringValue",
  47. "Int32Value", "UInt32Value", "FloatValue",
  48. "Int64Value", "UInt64Value", "DoubleValue",
  49. "Duration", "Timestamp",
  50. "NullValue", "Struct", "Value", "ListValue":
  51. return string(s.Name())
  52. }
  53. }
  54. return ""
  55. }
  56. func isMessageSet(md protoreflect.MessageDescriptor) bool {
  57. ms, ok := md.(interface{ IsMessageSet() bool })
  58. return ok && ms.IsMessageSet()
  59. }