encode.go 9.4 KB

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