encode.go 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301
  1. // Copyright 2019 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 protojson
  5. import (
  6. "encoding/base64"
  7. "fmt"
  8. "sort"
  9. "google.golang.org/protobuf/internal/encoding/json"
  10. "google.golang.org/protobuf/internal/encoding/messageset"
  11. "google.golang.org/protobuf/internal/errors"
  12. "google.golang.org/protobuf/internal/flags"
  13. "google.golang.org/protobuf/internal/pragma"
  14. "google.golang.org/protobuf/proto"
  15. pref "google.golang.org/protobuf/reflect/protoreflect"
  16. "google.golang.org/protobuf/reflect/protoregistry"
  17. )
  18. // Marshal writes the given proto.Message in JSON format using default options.
  19. func Marshal(m proto.Message) ([]byte, error) {
  20. return MarshalOptions{}.Marshal(m)
  21. }
  22. // MarshalOptions is a configurable JSON format marshaler.
  23. type MarshalOptions struct {
  24. pragma.NoUnkeyedLiterals
  25. // AllowPartial allows messages that have missing required fields to marshal
  26. // without returning an error. If AllowPartial is false (the default),
  27. // Marshal will return error if there are any missing required fields.
  28. AllowPartial bool
  29. // If Indent is a non-empty string, it causes entries for an Array or Object
  30. // to be preceded by the indent and trailed by a newline. Indent can only be
  31. // composed of space or tab characters.
  32. Indent string
  33. // Resolver is used for looking up types when expanding google.protobuf.Any
  34. // messages. If nil, this defaults to using protoregistry.GlobalTypes.
  35. Resolver interface {
  36. protoregistry.ExtensionTypeResolver
  37. protoregistry.MessageTypeResolver
  38. }
  39. encoder *json.Encoder
  40. }
  41. // Marshal marshals the given proto.Message in the JSON format using options in
  42. // MarshalOptions.
  43. func (o MarshalOptions) Marshal(m proto.Message) ([]byte, error) {
  44. var err error
  45. o.encoder, err = json.NewEncoder(o.Indent)
  46. if err != nil {
  47. return nil, err
  48. }
  49. if o.Resolver == nil {
  50. o.Resolver = protoregistry.GlobalTypes
  51. }
  52. err = o.marshalMessage(m.ProtoReflect())
  53. if err != nil {
  54. return nil, err
  55. }
  56. if o.AllowPartial {
  57. return o.encoder.Bytes(), nil
  58. }
  59. return o.encoder.Bytes(), proto.IsInitialized(m)
  60. }
  61. // marshalMessage marshals the given protoreflect.Message.
  62. func (o MarshalOptions) marshalMessage(m pref.Message) error {
  63. if isCustomType(m.Descriptor().FullName()) {
  64. return o.marshalCustomType(m)
  65. }
  66. o.encoder.StartObject()
  67. defer o.encoder.EndObject()
  68. if err := o.marshalFields(m); err != nil {
  69. return err
  70. }
  71. return nil
  72. }
  73. // marshalFields marshals the fields in the given protoreflect.Message.
  74. func (o MarshalOptions) marshalFields(m pref.Message) error {
  75. messageDesc := m.Descriptor()
  76. if !flags.ProtoLegacy && messageset.IsMessageSet(messageDesc) {
  77. return errors.New("no support for proto1 MessageSets")
  78. }
  79. // Marshal out known fields.
  80. fieldDescs := messageDesc.Fields()
  81. for i := 0; i < fieldDescs.Len(); i++ {
  82. fd := fieldDescs.Get(i)
  83. if !m.Has(fd) {
  84. continue
  85. }
  86. name := fd.JSONName()
  87. val := m.Get(fd)
  88. if err := o.encoder.WriteName(name); err != nil {
  89. return err
  90. }
  91. if err := o.marshalValue(val, fd); err != nil {
  92. return err
  93. }
  94. }
  95. // Marshal out extensions.
  96. if err := o.marshalExtensions(m); err != nil {
  97. return err
  98. }
  99. return nil
  100. }
  101. // marshalValue marshals the given protoreflect.Value.
  102. func (o MarshalOptions) marshalValue(val pref.Value, fd pref.FieldDescriptor) error {
  103. switch {
  104. case fd.IsList():
  105. return o.marshalList(val.List(), fd)
  106. case fd.IsMap():
  107. return o.marshalMap(val.Map(), fd)
  108. default:
  109. return o.marshalSingular(val, fd)
  110. }
  111. }
  112. // marshalSingular marshals the given non-repeated field value. This includes
  113. // all scalar types, enums, messages, and groups.
  114. func (o MarshalOptions) marshalSingular(val pref.Value, fd pref.FieldDescriptor) error {
  115. switch kind := fd.Kind(); kind {
  116. case pref.BoolKind:
  117. o.encoder.WriteBool(val.Bool())
  118. case pref.StringKind:
  119. if err := o.encoder.WriteString(val.String()); err != nil {
  120. return err
  121. }
  122. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind:
  123. o.encoder.WriteInt(val.Int())
  124. case pref.Uint32Kind, pref.Fixed32Kind:
  125. o.encoder.WriteUint(val.Uint())
  126. case pref.Int64Kind, pref.Sint64Kind, pref.Uint64Kind,
  127. pref.Sfixed64Kind, pref.Fixed64Kind:
  128. // 64-bit integers are written out as JSON string.
  129. o.encoder.WriteString(val.String())
  130. case pref.FloatKind:
  131. // Encoder.WriteFloat handles the special numbers NaN and infinites.
  132. o.encoder.WriteFloat(val.Float(), 32)
  133. case pref.DoubleKind:
  134. // Encoder.WriteFloat handles the special numbers NaN and infinites.
  135. o.encoder.WriteFloat(val.Float(), 64)
  136. case pref.BytesKind:
  137. err := o.encoder.WriteString(base64.StdEncoding.EncodeToString(val.Bytes()))
  138. if err != nil {
  139. return err
  140. }
  141. case pref.EnumKind:
  142. if fd.Enum().FullName() == "google.protobuf.NullValue" {
  143. o.encoder.WriteNull()
  144. } else if desc := fd.Enum().Values().ByNumber(val.Enum()); desc != nil {
  145. err := o.encoder.WriteString(string(desc.Name()))
  146. if err != nil {
  147. return err
  148. }
  149. } else {
  150. // Use numeric value if there is no enum value descriptor.
  151. o.encoder.WriteInt(int64(val.Enum()))
  152. }
  153. case pref.MessageKind, pref.GroupKind:
  154. if err := o.marshalMessage(val.Message()); err != nil {
  155. return err
  156. }
  157. default:
  158. panic(fmt.Sprintf("%v has unknown kind: %v", fd.FullName(), kind))
  159. }
  160. return nil
  161. }
  162. // marshalList marshals the given protoreflect.List.
  163. func (o MarshalOptions) marshalList(list pref.List, fd pref.FieldDescriptor) error {
  164. o.encoder.StartArray()
  165. defer o.encoder.EndArray()
  166. for i := 0; i < list.Len(); i++ {
  167. item := list.Get(i)
  168. if err := o.marshalSingular(item, fd); err != nil {
  169. return err
  170. }
  171. }
  172. return nil
  173. }
  174. type mapEntry struct {
  175. key pref.MapKey
  176. value pref.Value
  177. }
  178. // marshalMap marshals given protoreflect.Map.
  179. func (o MarshalOptions) marshalMap(mmap pref.Map, fd pref.FieldDescriptor) error {
  180. o.encoder.StartObject()
  181. defer o.encoder.EndObject()
  182. // Get a sorted list based on keyType first.
  183. entries := make([]mapEntry, 0, mmap.Len())
  184. mmap.Range(func(key pref.MapKey, val pref.Value) bool {
  185. entries = append(entries, mapEntry{key: key, value: val})
  186. return true
  187. })
  188. sortMap(fd.MapKey().Kind(), entries)
  189. // Write out sorted list.
  190. for _, entry := range entries {
  191. if err := o.encoder.WriteName(entry.key.String()); err != nil {
  192. return err
  193. }
  194. if err := o.marshalSingular(entry.value, fd.MapValue()); err != nil {
  195. return err
  196. }
  197. }
  198. return nil
  199. }
  200. // sortMap orders list based on value of key field for deterministic ordering.
  201. func sortMap(keyKind pref.Kind, values []mapEntry) {
  202. sort.Slice(values, func(i, j int) bool {
  203. switch keyKind {
  204. case pref.Int32Kind, pref.Sint32Kind, pref.Sfixed32Kind,
  205. pref.Int64Kind, pref.Sint64Kind, pref.Sfixed64Kind:
  206. return values[i].key.Int() < values[j].key.Int()
  207. case pref.Uint32Kind, pref.Fixed32Kind,
  208. pref.Uint64Kind, pref.Fixed64Kind:
  209. return values[i].key.Uint() < values[j].key.Uint()
  210. }
  211. return values[i].key.String() < values[j].key.String()
  212. })
  213. }
  214. // marshalExtensions marshals extension fields.
  215. func (o MarshalOptions) marshalExtensions(m pref.Message) error {
  216. type entry struct {
  217. key string
  218. value pref.Value
  219. desc pref.FieldDescriptor
  220. }
  221. // Get a sorted list based on field key first.
  222. var entries []entry
  223. m.Range(func(fd pref.FieldDescriptor, v pref.Value) bool {
  224. if !fd.IsExtension() {
  225. return true
  226. }
  227. // For MessageSet extensions, the name used is the parent message.
  228. name := fd.FullName()
  229. if messageset.IsMessageSetExtension(fd) {
  230. name = name.Parent()
  231. }
  232. // Use [name] format for JSON field name.
  233. entries = append(entries, entry{
  234. key: string(name),
  235. value: v,
  236. desc: fd,
  237. })
  238. return true
  239. })
  240. // Sort extensions lexicographically.
  241. sort.Slice(entries, func(i, j int) bool {
  242. return entries[i].key < entries[j].key
  243. })
  244. // Write out sorted list.
  245. for _, entry := range entries {
  246. // JSON field name is the proto field name enclosed in [], similar to
  247. // textproto. This is consistent with Go v1 lib. C++ lib v3.7.0 does not
  248. // marshal out extension fields.
  249. if err := o.encoder.WriteName("[" + entry.key + "]"); err != nil {
  250. return err
  251. }
  252. if err := o.marshalValue(entry.value, entry.desc); err != nil {
  253. return err
  254. }
  255. }
  256. return nil
  257. }