encode.go 10 KB

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