encode.go 9.4 KB

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