JsonFormatter.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920
  1. #region Copyright notice and license
  2. // Protocol Buffers - Google's data interchange format
  3. // Copyright 2015 Google Inc. All rights reserved.
  4. // https://developers.google.com/protocol-buffers/
  5. //
  6. // Redistribution and use in source and binary forms, with or without
  7. // modification, are permitted provided that the following conditions are
  8. // met:
  9. //
  10. // * Redistributions of source code must retain the above copyright
  11. // notice, this list of conditions and the following disclaimer.
  12. // * Redistributions in binary form must reproduce the above
  13. // copyright notice, this list of conditions and the following disclaimer
  14. // in the documentation and/or other materials provided with the
  15. // distribution.
  16. // * Neither the name of Google Inc. nor the names of its
  17. // contributors may be used to endorse or promote products derived from
  18. // this software without specific prior written permission.
  19. //
  20. // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
  21. // "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
  22. // LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
  23. // A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
  24. // OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
  25. // SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
  26. // LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
  27. // DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
  28. // THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  29. // (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
  30. // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  31. #endregion
  32. using System;
  33. using System.Collections;
  34. using System.Globalization;
  35. using System.Text;
  36. using Google.Protobuf.Reflection;
  37. using Google.Protobuf.WellKnownTypes;
  38. using System.IO;
  39. using System.Linq;
  40. using System.Collections.Generic;
  41. using System.Reflection;
  42. namespace Google.Protobuf
  43. {
  44. /// <summary>
  45. /// Reflection-based converter from messages to JSON.
  46. /// </summary>
  47. /// <remarks>
  48. /// <para>
  49. /// Instances of this class are thread-safe, with no mutable state.
  50. /// </para>
  51. /// <para>
  52. /// This is a simple start to get JSON formatting working. As it's reflection-based,
  53. /// it's not as quick as baking calls into generated messages - but is a simpler implementation.
  54. /// (This code is generally not heavily optimized.)
  55. /// </para>
  56. /// </remarks>
  57. public sealed class JsonFormatter
  58. {
  59. internal const string AnyTypeUrlField = "@type";
  60. internal const string AnyDiagnosticValueField = "@value";
  61. internal const string AnyWellKnownTypeValueField = "value";
  62. private const string TypeUrlPrefix = "type.googleapis.com";
  63. private const string NameValueSeparator = ": ";
  64. private const string PropertySeparator = ", ";
  65. /// <summary>
  66. /// Returns a formatter using the default settings.
  67. /// </summary>
  68. public static JsonFormatter Default { get; } = new JsonFormatter(Settings.Default);
  69. // A JSON formatter which *only* exists
  70. private static readonly JsonFormatter diagnosticFormatter = new JsonFormatter(Settings.Default);
  71. /// <summary>
  72. /// The JSON representation of the first 160 characters of Unicode.
  73. /// Empty strings are replaced by the static constructor.
  74. /// </summary>
  75. private static readonly string[] CommonRepresentations = {
  76. // C0 (ASCII and derivatives) control characters
  77. "\\u0000", "\\u0001", "\\u0002", "\\u0003", // 0x00
  78. "\\u0004", "\\u0005", "\\u0006", "\\u0007",
  79. "\\b", "\\t", "\\n", "\\u000b",
  80. "\\f", "\\r", "\\u000e", "\\u000f",
  81. "\\u0010", "\\u0011", "\\u0012", "\\u0013", // 0x10
  82. "\\u0014", "\\u0015", "\\u0016", "\\u0017",
  83. "\\u0018", "\\u0019", "\\u001a", "\\u001b",
  84. "\\u001c", "\\u001d", "\\u001e", "\\u001f",
  85. // Escaping of " and \ are required by www.json.org string definition.
  86. // Escaping of < and > are required for HTML security.
  87. "", "", "\\\"", "", "", "", "", "", // 0x20
  88. "", "", "", "", "", "", "", "",
  89. "", "", "", "", "", "", "", "", // 0x30
  90. "", "", "", "", "\\u003c", "", "\\u003e", "",
  91. "", "", "", "", "", "", "", "", // 0x40
  92. "", "", "", "", "", "", "", "",
  93. "", "", "", "", "", "", "", "", // 0x50
  94. "", "", "", "", "\\\\", "", "", "",
  95. "", "", "", "", "", "", "", "", // 0x60
  96. "", "", "", "", "", "", "", "",
  97. "", "", "", "", "", "", "", "", // 0x70
  98. "", "", "", "", "", "", "", "\\u007f",
  99. // C1 (ISO 8859 and Unicode) extended control characters
  100. "\\u0080", "\\u0081", "\\u0082", "\\u0083", // 0x80
  101. "\\u0084", "\\u0085", "\\u0086", "\\u0087",
  102. "\\u0088", "\\u0089", "\\u008a", "\\u008b",
  103. "\\u008c", "\\u008d", "\\u008e", "\\u008f",
  104. "\\u0090", "\\u0091", "\\u0092", "\\u0093", // 0x90
  105. "\\u0094", "\\u0095", "\\u0096", "\\u0097",
  106. "\\u0098", "\\u0099", "\\u009a", "\\u009b",
  107. "\\u009c", "\\u009d", "\\u009e", "\\u009f"
  108. };
  109. static JsonFormatter()
  110. {
  111. for (int i = 0; i < CommonRepresentations.Length; i++)
  112. {
  113. if (CommonRepresentations[i] == "")
  114. {
  115. CommonRepresentations[i] = ((char) i).ToString();
  116. }
  117. }
  118. }
  119. private readonly Settings settings;
  120. private bool DiagnosticOnly => ReferenceEquals(this, diagnosticFormatter);
  121. /// <summary>
  122. /// Creates a new formatted with the given settings.
  123. /// </summary>
  124. /// <param name="settings">The settings.</param>
  125. public JsonFormatter(Settings settings)
  126. {
  127. this.settings = settings;
  128. }
  129. /// <summary>
  130. /// Formats the specified message as JSON.
  131. /// </summary>
  132. /// <param name="message">The message to format.</param>
  133. /// <returns>The formatted message.</returns>
  134. public string Format(IMessage message)
  135. {
  136. var writer = new StringWriter();
  137. Format(message, writer);
  138. return writer.ToString();
  139. }
  140. /// <summary>
  141. /// Formats the specified message as JSON.
  142. /// </summary>
  143. /// <param name="message">The message to format.</param>
  144. /// <param name="writer">The TextWriter to write the formatted message to.</param>
  145. /// <returns>The formatted message.</returns>
  146. public void Format(IMessage message, TextWriter writer)
  147. {
  148. ProtoPreconditions.CheckNotNull(message, nameof(message));
  149. ProtoPreconditions.CheckNotNull(writer, nameof(writer));
  150. if (message.Descriptor.IsWellKnownType)
  151. {
  152. WriteWellKnownTypeValue(writer, message.Descriptor, message);
  153. }
  154. else
  155. {
  156. WriteMessage(writer, message);
  157. }
  158. }
  159. /// <summary>
  160. /// Converts a message to JSON for diagnostic purposes with no extra context.
  161. /// </summary>
  162. /// <remarks>
  163. /// <para>
  164. /// This differs from calling <see cref="Format(IMessage)"/> on the default JSON
  165. /// formatter in its handling of <see cref="Any"/>. As no type registry is available
  166. /// in <see cref="object.ToString"/> calls, the normal way of resolving the type of
  167. /// an <c>Any</c> message cannot be applied. Instead, a JSON property named <c>@value</c>
  168. /// is included with the base64 data from the <see cref="Any.Value"/> property of the message.
  169. /// </para>
  170. /// <para>The value returned by this method is only designed to be used for diagnostic
  171. /// purposes. It may not be parsable by <see cref="JsonParser"/>, and may not be parsable
  172. /// by other Protocol Buffer implementations.</para>
  173. /// </remarks>
  174. /// <param name="message">The message to format for diagnostic purposes.</param>
  175. /// <returns>The diagnostic-only JSON representation of the message</returns>
  176. public static string ToDiagnosticString(IMessage message)
  177. {
  178. ProtoPreconditions.CheckNotNull(message, nameof(message));
  179. return diagnosticFormatter.Format(message);
  180. }
  181. private void WriteMessage(TextWriter writer, IMessage message)
  182. {
  183. if (message == null)
  184. {
  185. WriteNull(writer);
  186. return;
  187. }
  188. if (DiagnosticOnly)
  189. {
  190. ICustomDiagnosticMessage customDiagnosticMessage = message as ICustomDiagnosticMessage;
  191. if (customDiagnosticMessage != null)
  192. {
  193. writer.Write(customDiagnosticMessage.ToDiagnosticString());
  194. return;
  195. }
  196. }
  197. writer.Write("{ ");
  198. bool writtenFields = WriteMessageFields(writer, message, false);
  199. writer.Write(writtenFields ? " }" : "}");
  200. }
  201. private bool WriteMessageFields(TextWriter writer, IMessage message, bool assumeFirstFieldWritten)
  202. {
  203. var fields = message.Descriptor.Fields;
  204. bool first = !assumeFirstFieldWritten;
  205. // First non-oneof fields
  206. foreach (var field in fields.InFieldNumberOrder())
  207. {
  208. var accessor = field.Accessor;
  209. if (field.ContainingOneof != null && field.ContainingOneof.Accessor.GetCaseFieldDescriptor(message) != field)
  210. {
  211. continue;
  212. }
  213. // Omit default values unless we're asked to format them, or they're oneofs (where the default
  214. // value is still formatted regardless, because that's how we preserve the oneof case).
  215. object value = accessor.GetValue(message);
  216. if (field.ContainingOneof == null && !settings.FormatDefaultValues && IsDefaultValue(accessor, value))
  217. {
  218. continue;
  219. }
  220. // Okay, all tests complete: let's write the field value...
  221. if (!first)
  222. {
  223. writer.Write(PropertySeparator);
  224. }
  225. WriteString(writer, accessor.Descriptor.JsonName);
  226. writer.Write(NameValueSeparator);
  227. WriteValue(writer, value);
  228. first = false;
  229. }
  230. return !first;
  231. }
  232. // Converted from java/core/src/main/java/com/google/protobuf/Descriptors.java
  233. internal static string ToJsonName(string name)
  234. {
  235. StringBuilder result = new StringBuilder(name.Length);
  236. bool isNextUpperCase = false;
  237. foreach (char ch in name)
  238. {
  239. if (ch == '_')
  240. {
  241. isNextUpperCase = true;
  242. }
  243. else if (isNextUpperCase)
  244. {
  245. result.Append(char.ToUpperInvariant(ch));
  246. isNextUpperCase = false;
  247. }
  248. else
  249. {
  250. result.Append(ch);
  251. }
  252. }
  253. return result.ToString();
  254. }
  255. internal static string FromJsonName(string name)
  256. {
  257. StringBuilder result = new StringBuilder(name.Length);
  258. foreach (char ch in name)
  259. {
  260. if (char.IsUpper(ch))
  261. {
  262. result.Append('_');
  263. result.Append(char.ToLowerInvariant(ch));
  264. }
  265. else
  266. {
  267. result.Append(ch);
  268. }
  269. }
  270. return result.ToString();
  271. }
  272. private static void WriteNull(TextWriter writer)
  273. {
  274. writer.Write("null");
  275. }
  276. private static bool IsDefaultValue(IFieldAccessor accessor, object value)
  277. {
  278. if (accessor.Descriptor.IsMap)
  279. {
  280. IDictionary dictionary = (IDictionary) value;
  281. return dictionary.Count == 0;
  282. }
  283. if (accessor.Descriptor.IsRepeated)
  284. {
  285. IList list = (IList) value;
  286. return list.Count == 0;
  287. }
  288. switch (accessor.Descriptor.FieldType)
  289. {
  290. case FieldType.Bool:
  291. return (bool) value == false;
  292. case FieldType.Bytes:
  293. return (ByteString) value == ByteString.Empty;
  294. case FieldType.String:
  295. return (string) value == "";
  296. case FieldType.Double:
  297. return (double) value == 0.0;
  298. case FieldType.SInt32:
  299. case FieldType.Int32:
  300. case FieldType.SFixed32:
  301. case FieldType.Enum:
  302. return (int) value == 0;
  303. case FieldType.Fixed32:
  304. case FieldType.UInt32:
  305. return (uint) value == 0;
  306. case FieldType.Fixed64:
  307. case FieldType.UInt64:
  308. return (ulong) value == 0;
  309. case FieldType.SFixed64:
  310. case FieldType.Int64:
  311. case FieldType.SInt64:
  312. return (long) value == 0;
  313. case FieldType.Float:
  314. return (float) value == 0f;
  315. case FieldType.Message:
  316. case FieldType.Group: // Never expect to get this, but...
  317. return value == null;
  318. default:
  319. throw new ArgumentException("Invalid field type");
  320. }
  321. }
  322. /// <summary>
  323. /// Writes a single value to the given writer as JSON. Only types understood by
  324. /// Protocol Buffers can be written in this way. This method is only exposed for
  325. /// advanced use cases; most users should be using <see cref="Format(IMessage)"/>
  326. /// or <see cref="Format(IMessage, TextWriter)"/>.
  327. /// </summary>
  328. /// <param name="writer">The writer to write the value to. Must not be null.</param>
  329. /// <param name="value">The value to write. May be null.</param>
  330. public void WriteValue(TextWriter writer, object value)
  331. {
  332. if (value == null)
  333. {
  334. WriteNull(writer);
  335. }
  336. else if (value is bool)
  337. {
  338. writer.Write((bool)value ? "true" : "false");
  339. }
  340. else if (value is ByteString)
  341. {
  342. // Nothing in Base64 needs escaping
  343. writer.Write('"');
  344. writer.Write(((ByteString)value).ToBase64());
  345. writer.Write('"');
  346. }
  347. else if (value is string)
  348. {
  349. WriteString(writer, (string)value);
  350. }
  351. else if (value is IDictionary)
  352. {
  353. WriteDictionary(writer, (IDictionary)value);
  354. }
  355. else if (value is IList)
  356. {
  357. WriteList(writer, (IList)value);
  358. }
  359. else if (value is int || value is uint)
  360. {
  361. IFormattable formattable = (IFormattable) value;
  362. writer.Write(formattable.ToString("d", CultureInfo.InvariantCulture));
  363. }
  364. else if (value is long || value is ulong)
  365. {
  366. writer.Write('"');
  367. IFormattable formattable = (IFormattable) value;
  368. writer.Write(formattable.ToString("d", CultureInfo.InvariantCulture));
  369. writer.Write('"');
  370. }
  371. else if (value is System.Enum)
  372. {
  373. if (settings.FormatEnumsAsIntegers)
  374. {
  375. WriteValue(writer, (int)value);
  376. }
  377. else
  378. {
  379. string name = OriginalEnumValueHelper.GetOriginalName(value);
  380. if (name != null)
  381. {
  382. WriteString(writer, name);
  383. }
  384. else
  385. {
  386. WriteValue(writer, (int)value);
  387. }
  388. }
  389. }
  390. else if (value is float || value is double)
  391. {
  392. string text = ((IFormattable) value).ToString("r", CultureInfo.InvariantCulture);
  393. if (text == "NaN" || text == "Infinity" || text == "-Infinity")
  394. {
  395. writer.Write('"');
  396. writer.Write(text);
  397. writer.Write('"');
  398. }
  399. else
  400. {
  401. writer.Write(text);
  402. }
  403. }
  404. else if (value is IMessage)
  405. {
  406. Format((IMessage)value, writer);
  407. }
  408. else
  409. {
  410. throw new ArgumentException("Unable to format value of type " + value.GetType());
  411. }
  412. }
  413. /// <summary>
  414. /// Central interception point for well-known type formatting. Any well-known types which
  415. /// don't need special handling can fall back to WriteMessage. We avoid assuming that the
  416. /// values are using the embedded well-known types, in order to allow for dynamic messages
  417. /// in the future.
  418. /// </summary>
  419. private void WriteWellKnownTypeValue(TextWriter writer, MessageDescriptor descriptor, object value)
  420. {
  421. // Currently, we can never actually get here, because null values are always handled by the caller. But if we *could*,
  422. // this would do the right thing.
  423. if (value == null)
  424. {
  425. WriteNull(writer);
  426. return;
  427. }
  428. // For wrapper types, the value will either be the (possibly boxed) "native" value,
  429. // or the message itself if we're formatting it at the top level (e.g. just calling ToString on the object itself).
  430. // If it's the message form, we can extract the value first, which *will* be the (possibly boxed) native value,
  431. // and then proceed, writing it as if we were definitely in a field. (We never need to wrap it in an extra string...
  432. // WriteValue will do the right thing.)
  433. if (descriptor.IsWrapperType)
  434. {
  435. if (value is IMessage)
  436. {
  437. var message = (IMessage) value;
  438. value = message.Descriptor.Fields[WrappersReflection.WrapperValueFieldNumber].Accessor.GetValue(message);
  439. }
  440. WriteValue(writer, value);
  441. return;
  442. }
  443. if (descriptor.FullName == Timestamp.Descriptor.FullName)
  444. {
  445. WriteTimestamp(writer, (IMessage)value);
  446. return;
  447. }
  448. if (descriptor.FullName == Duration.Descriptor.FullName)
  449. {
  450. WriteDuration(writer, (IMessage)value);
  451. return;
  452. }
  453. if (descriptor.FullName == FieldMask.Descriptor.FullName)
  454. {
  455. WriteFieldMask(writer, (IMessage)value);
  456. return;
  457. }
  458. if (descriptor.FullName == Struct.Descriptor.FullName)
  459. {
  460. WriteStruct(writer, (IMessage)value);
  461. return;
  462. }
  463. if (descriptor.FullName == ListValue.Descriptor.FullName)
  464. {
  465. var fieldAccessor = descriptor.Fields[ListValue.ValuesFieldNumber].Accessor;
  466. WriteList(writer, (IList)fieldAccessor.GetValue((IMessage)value));
  467. return;
  468. }
  469. if (descriptor.FullName == Value.Descriptor.FullName)
  470. {
  471. WriteStructFieldValue(writer, (IMessage)value);
  472. return;
  473. }
  474. if (descriptor.FullName == Any.Descriptor.FullName)
  475. {
  476. WriteAny(writer, (IMessage)value);
  477. return;
  478. }
  479. WriteMessage(writer, (IMessage)value);
  480. }
  481. private void WriteTimestamp(TextWriter writer, IMessage value)
  482. {
  483. // TODO: In the common case where this *is* using the built-in Timestamp type, we could
  484. // avoid all the reflection at this point, by casting to Timestamp. In the interests of
  485. // avoiding subtle bugs, don't do that until we've implemented DynamicMessage so that we can prove
  486. // it still works in that case.
  487. int nanos = (int) value.Descriptor.Fields[Timestamp.NanosFieldNumber].Accessor.GetValue(value);
  488. long seconds = (long) value.Descriptor.Fields[Timestamp.SecondsFieldNumber].Accessor.GetValue(value);
  489. writer.Write(Timestamp.ToJson(seconds, nanos, DiagnosticOnly));
  490. }
  491. private void WriteDuration(TextWriter writer, IMessage value)
  492. {
  493. // TODO: Same as for WriteTimestamp
  494. int nanos = (int) value.Descriptor.Fields[Duration.NanosFieldNumber].Accessor.GetValue(value);
  495. long seconds = (long) value.Descriptor.Fields[Duration.SecondsFieldNumber].Accessor.GetValue(value);
  496. writer.Write(Duration.ToJson(seconds, nanos, DiagnosticOnly));
  497. }
  498. private void WriteFieldMask(TextWriter writer, IMessage value)
  499. {
  500. var paths = (IList<string>) value.Descriptor.Fields[FieldMask.PathsFieldNumber].Accessor.GetValue(value);
  501. writer.Write(FieldMask.ToJson(paths, DiagnosticOnly));
  502. }
  503. private void WriteAny(TextWriter writer, IMessage value)
  504. {
  505. if (DiagnosticOnly)
  506. {
  507. WriteDiagnosticOnlyAny(writer, value);
  508. return;
  509. }
  510. string typeUrl = (string) value.Descriptor.Fields[Any.TypeUrlFieldNumber].Accessor.GetValue(value);
  511. ByteString data = (ByteString) value.Descriptor.Fields[Any.ValueFieldNumber].Accessor.GetValue(value);
  512. string typeName = Any.GetTypeName(typeUrl);
  513. MessageDescriptor descriptor = settings.TypeRegistry.Find(typeName);
  514. if (descriptor == null)
  515. {
  516. throw new InvalidOperationException($"Type registry has no descriptor for type name '{typeName}'");
  517. }
  518. IMessage message = descriptor.Parser.ParseFrom(data);
  519. writer.Write("{ ");
  520. WriteString(writer, AnyTypeUrlField);
  521. writer.Write(NameValueSeparator);
  522. WriteString(writer, typeUrl);
  523. if (descriptor.IsWellKnownType)
  524. {
  525. writer.Write(PropertySeparator);
  526. WriteString(writer, AnyWellKnownTypeValueField);
  527. writer.Write(NameValueSeparator);
  528. WriteWellKnownTypeValue(writer, descriptor, message);
  529. }
  530. else
  531. {
  532. WriteMessageFields(writer, message, true);
  533. }
  534. writer.Write(" }");
  535. }
  536. private void WriteDiagnosticOnlyAny(TextWriter writer, IMessage value)
  537. {
  538. string typeUrl = (string) value.Descriptor.Fields[Any.TypeUrlFieldNumber].Accessor.GetValue(value);
  539. ByteString data = (ByteString) value.Descriptor.Fields[Any.ValueFieldNumber].Accessor.GetValue(value);
  540. writer.Write("{ ");
  541. WriteString(writer, AnyTypeUrlField);
  542. writer.Write(NameValueSeparator);
  543. WriteString(writer, typeUrl);
  544. writer.Write(PropertySeparator);
  545. WriteString(writer, AnyDiagnosticValueField);
  546. writer.Write(NameValueSeparator);
  547. writer.Write('"');
  548. writer.Write(data.ToBase64());
  549. writer.Write('"');
  550. writer.Write(" }");
  551. }
  552. private void WriteStruct(TextWriter writer, IMessage message)
  553. {
  554. writer.Write("{ ");
  555. IDictionary fields = (IDictionary) message.Descriptor.Fields[Struct.FieldsFieldNumber].Accessor.GetValue(message);
  556. bool first = true;
  557. foreach (DictionaryEntry entry in fields)
  558. {
  559. string key = (string) entry.Key;
  560. IMessage value = (IMessage) entry.Value;
  561. if (string.IsNullOrEmpty(key) || value == null)
  562. {
  563. throw new InvalidOperationException("Struct fields cannot have an empty key or a null value.");
  564. }
  565. if (!first)
  566. {
  567. writer.Write(PropertySeparator);
  568. }
  569. WriteString(writer, key);
  570. writer.Write(NameValueSeparator);
  571. WriteStructFieldValue(writer, value);
  572. first = false;
  573. }
  574. writer.Write(first ? "}" : " }");
  575. }
  576. private void WriteStructFieldValue(TextWriter writer, IMessage message)
  577. {
  578. var specifiedField = message.Descriptor.Oneofs[0].Accessor.GetCaseFieldDescriptor(message);
  579. if (specifiedField == null)
  580. {
  581. throw new InvalidOperationException("Value message must contain a value for the oneof.");
  582. }
  583. object value = specifiedField.Accessor.GetValue(message);
  584. switch (specifiedField.FieldNumber)
  585. {
  586. case Value.BoolValueFieldNumber:
  587. case Value.StringValueFieldNumber:
  588. case Value.NumberValueFieldNumber:
  589. WriteValue(writer, value);
  590. return;
  591. case Value.StructValueFieldNumber:
  592. case Value.ListValueFieldNumber:
  593. // Structs and ListValues are nested messages, and already well-known types.
  594. var nestedMessage = (IMessage) specifiedField.Accessor.GetValue(message);
  595. WriteWellKnownTypeValue(writer, nestedMessage.Descriptor, nestedMessage);
  596. return;
  597. case Value.NullValueFieldNumber:
  598. WriteNull(writer);
  599. return;
  600. default:
  601. throw new InvalidOperationException("Unexpected case in struct field: " + specifiedField.FieldNumber);
  602. }
  603. }
  604. internal void WriteList(TextWriter writer, IList list)
  605. {
  606. writer.Write("[ ");
  607. bool first = true;
  608. foreach (var value in list)
  609. {
  610. if (!first)
  611. {
  612. writer.Write(PropertySeparator);
  613. }
  614. WriteValue(writer, value);
  615. first = false;
  616. }
  617. writer.Write(first ? "]" : " ]");
  618. }
  619. internal void WriteDictionary(TextWriter writer, IDictionary dictionary)
  620. {
  621. writer.Write("{ ");
  622. bool first = true;
  623. // This will box each pair. Could use IDictionaryEnumerator, but that's ugly in terms of disposal.
  624. foreach (DictionaryEntry pair in dictionary)
  625. {
  626. if (!first)
  627. {
  628. writer.Write(PropertySeparator);
  629. }
  630. string keyText;
  631. if (pair.Key is string)
  632. {
  633. keyText = (string) pair.Key;
  634. }
  635. else if (pair.Key is bool)
  636. {
  637. keyText = (bool) pair.Key ? "true" : "false";
  638. }
  639. else if (pair.Key is int || pair.Key is uint | pair.Key is long || pair.Key is ulong)
  640. {
  641. keyText = ((IFormattable) pair.Key).ToString("d", CultureInfo.InvariantCulture);
  642. }
  643. else
  644. {
  645. if (pair.Key == null)
  646. {
  647. throw new ArgumentException("Dictionary has entry with null key");
  648. }
  649. throw new ArgumentException("Unhandled dictionary key type: " + pair.Key.GetType());
  650. }
  651. WriteString(writer, keyText);
  652. writer.Write(NameValueSeparator);
  653. WriteValue(writer, pair.Value);
  654. first = false;
  655. }
  656. writer.Write(first ? "}" : " }");
  657. }
  658. /// <summary>
  659. /// Writes a string (including leading and trailing double quotes) to a builder, escaping as required.
  660. /// </summary>
  661. /// <remarks>
  662. /// Other than surrogate pair handling, this code is mostly taken from src/google/protobuf/util/internal/json_escaping.cc.
  663. /// </remarks>
  664. internal static void WriteString(TextWriter writer, string text)
  665. {
  666. writer.Write('"');
  667. for (int i = 0; i < text.Length; i++)
  668. {
  669. char c = text[i];
  670. if (c < 0xa0)
  671. {
  672. writer.Write(CommonRepresentations[c]);
  673. continue;
  674. }
  675. if (char.IsHighSurrogate(c))
  676. {
  677. // Encountered first part of a surrogate pair.
  678. // Check that we have the whole pair, and encode both parts as hex.
  679. i++;
  680. if (i == text.Length || !char.IsLowSurrogate(text[i]))
  681. {
  682. throw new ArgumentException("String contains low surrogate not followed by high surrogate");
  683. }
  684. HexEncodeUtf16CodeUnit(writer, c);
  685. HexEncodeUtf16CodeUnit(writer, text[i]);
  686. continue;
  687. }
  688. else if (char.IsLowSurrogate(c))
  689. {
  690. throw new ArgumentException("String contains high surrogate not preceded by low surrogate");
  691. }
  692. switch ((uint) c)
  693. {
  694. // These are not required by json spec
  695. // but used to prevent security bugs in javascript.
  696. case 0xfeff: // Zero width no-break space
  697. case 0xfff9: // Interlinear annotation anchor
  698. case 0xfffa: // Interlinear annotation separator
  699. case 0xfffb: // Interlinear annotation terminator
  700. case 0x00ad: // Soft-hyphen
  701. case 0x06dd: // Arabic end of ayah
  702. case 0x070f: // Syriac abbreviation mark
  703. case 0x17b4: // Khmer vowel inherent Aq
  704. case 0x17b5: // Khmer vowel inherent Aa
  705. HexEncodeUtf16CodeUnit(writer, c);
  706. break;
  707. default:
  708. if ((c >= 0x0600 && c <= 0x0603) || // Arabic signs
  709. (c >= 0x200b && c <= 0x200f) || // Zero width etc.
  710. (c >= 0x2028 && c <= 0x202e) || // Separators etc.
  711. (c >= 0x2060 && c <= 0x2064) || // Invisible etc.
  712. (c >= 0x206a && c <= 0x206f))
  713. {
  714. HexEncodeUtf16CodeUnit(writer, c);
  715. }
  716. else
  717. {
  718. // No handling of surrogates here - that's done earlier
  719. writer.Write(c);
  720. }
  721. break;
  722. }
  723. }
  724. writer.Write('"');
  725. }
  726. private const string Hex = "0123456789abcdef";
  727. private static void HexEncodeUtf16CodeUnit(TextWriter writer, char c)
  728. {
  729. writer.Write("\\u");
  730. writer.Write(Hex[(c >> 12) & 0xf]);
  731. writer.Write(Hex[(c >> 8) & 0xf]);
  732. writer.Write(Hex[(c >> 4) & 0xf]);
  733. writer.Write(Hex[(c >> 0) & 0xf]);
  734. }
  735. /// <summary>
  736. /// Settings controlling JSON formatting.
  737. /// </summary>
  738. public sealed class Settings
  739. {
  740. /// <summary>
  741. /// Default settings, as used by <see cref="JsonFormatter.Default"/>
  742. /// </summary>
  743. public static Settings Default { get; }
  744. // Workaround for the Mono compiler complaining about XML comments not being on
  745. // valid language elements.
  746. static Settings()
  747. {
  748. Default = new Settings(false);
  749. }
  750. /// <summary>
  751. /// Whether fields whose values are the default for the field type (e.g. 0 for integers)
  752. /// should be formatted (true) or omitted (false).
  753. /// </summary>
  754. public bool FormatDefaultValues { get; }
  755. /// <summary>
  756. /// The type registry used to format <see cref="Any"/> messages.
  757. /// </summary>
  758. public TypeRegistry TypeRegistry { get; }
  759. /// <summary>
  760. /// Whether to format enums as ints. Defaults to false.
  761. /// </summary>
  762. public bool FormatEnumsAsIntegers { get; }
  763. /// <summary>
  764. /// Creates a new <see cref="Settings"/> object with the specified formatting of default values
  765. /// and an empty type registry.
  766. /// </summary>
  767. /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param>
  768. public Settings(bool formatDefaultValues) : this(formatDefaultValues, TypeRegistry.Empty)
  769. {
  770. }
  771. /// <summary>
  772. /// Creates a new <see cref="Settings"/> object with the specified formatting of default values
  773. /// and type registry.
  774. /// </summary>
  775. /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param>
  776. /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages.</param>
  777. public Settings(bool formatDefaultValues, TypeRegistry typeRegistry) : this(formatDefaultValues, typeRegistry, false)
  778. {
  779. }
  780. /// <summary>
  781. /// Creates a new <see cref="Settings"/> object with the specified parameters.
  782. /// </summary>
  783. /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param>
  784. /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages. TypeRegistry.Empty will be used if it is null.</param>
  785. /// <param name="formatEnumsAsIntegers"><c>true</c> to format the enums as integers; <c>false</c> to format enums as enum names.</param>
  786. private Settings(bool formatDefaultValues,
  787. TypeRegistry typeRegistry,
  788. bool formatEnumsAsIntegers)
  789. {
  790. FormatDefaultValues = formatDefaultValues;
  791. TypeRegistry = typeRegistry ?? TypeRegistry.Empty;
  792. FormatEnumsAsIntegers = formatEnumsAsIntegers;
  793. }
  794. /// <summary>
  795. /// Creates a new <see cref="Settings"/> object with the specified formatting of default values and the current settings.
  796. /// </summary>
  797. /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param>
  798. public Settings WithFormatDefaultValues(bool formatDefaultValues) => new Settings(formatDefaultValues, TypeRegistry, FormatEnumsAsIntegers);
  799. /// <summary>
  800. /// Creates a new <see cref="Settings"/> object with the specified type registry and the current settings.
  801. /// </summary>
  802. /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages.</param>
  803. public Settings WithTypeRegistry(TypeRegistry typeRegistry) => new Settings(FormatDefaultValues, typeRegistry, FormatEnumsAsIntegers);
  804. /// <summary>
  805. /// Creates a new <see cref="Settings"/> object with the specified enums formatting option and the current settings.
  806. /// </summary>
  807. /// <param name="formatEnumsAsIntegers"><c>true</c> to format the enums as integers; <c>false</c> to format enums as enum names.</param>
  808. public Settings WithFormatEnumsAsIntegers(bool formatEnumsAsIntegers) => new Settings(FormatDefaultValues, TypeRegistry, formatEnumsAsIntegers);
  809. }
  810. // Effectively a cache of mapping from enum values to the original name as specified in the proto file,
  811. // fetched by reflection.
  812. // The need for this is unfortunate, as is its unbounded size, but realistically it shouldn't cause issues.
  813. private static class OriginalEnumValueHelper
  814. {
  815. // TODO: In the future we might want to use ConcurrentDictionary, at the point where all
  816. // the platforms we target have it.
  817. private static readonly Dictionary<System.Type, Dictionary<object, string>> dictionaries
  818. = new Dictionary<System.Type, Dictionary<object, string>>();
  819. internal static string GetOriginalName(object value)
  820. {
  821. var enumType = value.GetType();
  822. Dictionary<object, string> nameMapping;
  823. lock (dictionaries)
  824. {
  825. if (!dictionaries.TryGetValue(enumType, out nameMapping))
  826. {
  827. nameMapping = GetNameMapping(enumType);
  828. dictionaries[enumType] = nameMapping;
  829. }
  830. }
  831. string originalName;
  832. // If this returns false, originalName will be null, which is what we want.
  833. nameMapping.TryGetValue(value, out originalName);
  834. return originalName;
  835. }
  836. #if NET35
  837. // TODO: Consider adding functionality to TypeExtensions to avoid this difference.
  838. private static Dictionary<object, string> GetNameMapping(System.Type enumType) =>
  839. enumType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
  840. .Where(f => (f.GetCustomAttributes(typeof(OriginalNameAttribute), false)
  841. .FirstOrDefault() as OriginalNameAttribute)
  842. ?.PreferredAlias ?? true)
  843. .ToDictionary(f => f.GetValue(null),
  844. f => (f.GetCustomAttributes(typeof(OriginalNameAttribute), false)
  845. .FirstOrDefault() as OriginalNameAttribute)
  846. // If the attribute hasn't been applied, fall back to the name of the field.
  847. ?.Name ?? f.Name);
  848. #else
  849. private static Dictionary<object, string> GetNameMapping(System.Type enumType) =>
  850. enumType.GetTypeInfo().DeclaredFields
  851. .Where(f => f.IsStatic)
  852. .Where(f => f.GetCustomAttributes<OriginalNameAttribute>()
  853. .FirstOrDefault()?.PreferredAlias ?? true)
  854. .ToDictionary(f => f.GetValue(null),
  855. f => f.GetCustomAttributes<OriginalNameAttribute>()
  856. .FirstOrDefault()
  857. // If the attribute hasn't been applied, fall back to the name of the field.
  858. ?.Name ?? f.Name);
  859. #endif
  860. }
  861. }
  862. }