JsonFormatter.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902
  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. private static void WriteNull(TextWriter writer)
  256. {
  257. writer.Write("null");
  258. }
  259. private static bool IsDefaultValue(IFieldAccessor accessor, object value)
  260. {
  261. if (accessor.Descriptor.IsMap)
  262. {
  263. IDictionary dictionary = (IDictionary) value;
  264. return dictionary.Count == 0;
  265. }
  266. if (accessor.Descriptor.IsRepeated)
  267. {
  268. IList list = (IList) value;
  269. return list.Count == 0;
  270. }
  271. switch (accessor.Descriptor.FieldType)
  272. {
  273. case FieldType.Bool:
  274. return (bool) value == false;
  275. case FieldType.Bytes:
  276. return (ByteString) value == ByteString.Empty;
  277. case FieldType.String:
  278. return (string) value == "";
  279. case FieldType.Double:
  280. return (double) value == 0.0;
  281. case FieldType.SInt32:
  282. case FieldType.Int32:
  283. case FieldType.SFixed32:
  284. case FieldType.Enum:
  285. return (int) value == 0;
  286. case FieldType.Fixed32:
  287. case FieldType.UInt32:
  288. return (uint) value == 0;
  289. case FieldType.Fixed64:
  290. case FieldType.UInt64:
  291. return (ulong) value == 0;
  292. case FieldType.SFixed64:
  293. case FieldType.Int64:
  294. case FieldType.SInt64:
  295. return (long) value == 0;
  296. case FieldType.Float:
  297. return (float) value == 0f;
  298. case FieldType.Message:
  299. case FieldType.Group: // Never expect to get this, but...
  300. return value == null;
  301. default:
  302. throw new ArgumentException("Invalid field type");
  303. }
  304. }
  305. /// <summary>
  306. /// Writes a single value to the given writer as JSON. Only types understood by
  307. /// Protocol Buffers can be written in this way. This method is only exposed for
  308. /// advanced use cases; most users should be using <see cref="Format(IMessage)"/>
  309. /// or <see cref="Format(IMessage, TextWriter)"/>.
  310. /// </summary>
  311. /// <param name="writer">The writer to write the value to. Must not be null.</param>
  312. /// <param name="value">The value to write. May be null.</param>
  313. public void WriteValue(TextWriter writer, object value)
  314. {
  315. if (value == null)
  316. {
  317. WriteNull(writer);
  318. }
  319. else if (value is bool)
  320. {
  321. writer.Write((bool)value ? "true" : "false");
  322. }
  323. else if (value is ByteString)
  324. {
  325. // Nothing in Base64 needs escaping
  326. writer.Write('"');
  327. writer.Write(((ByteString)value).ToBase64());
  328. writer.Write('"');
  329. }
  330. else if (value is string)
  331. {
  332. WriteString(writer, (string)value);
  333. }
  334. else if (value is IDictionary)
  335. {
  336. WriteDictionary(writer, (IDictionary)value);
  337. }
  338. else if (value is IList)
  339. {
  340. WriteList(writer, (IList)value);
  341. }
  342. else if (value is int || value is uint)
  343. {
  344. IFormattable formattable = (IFormattable) value;
  345. writer.Write(formattable.ToString("d", CultureInfo.InvariantCulture));
  346. }
  347. else if (value is long || value is ulong)
  348. {
  349. writer.Write('"');
  350. IFormattable formattable = (IFormattable) value;
  351. writer.Write(formattable.ToString("d", CultureInfo.InvariantCulture));
  352. writer.Write('"');
  353. }
  354. else if (value is System.Enum)
  355. {
  356. if (settings.FormatEnumsAsIntegers)
  357. {
  358. WriteValue(writer, (int)value);
  359. }
  360. else
  361. {
  362. string name = OriginalEnumValueHelper.GetOriginalName(value);
  363. if (name != null)
  364. {
  365. WriteString(writer, name);
  366. }
  367. else
  368. {
  369. WriteValue(writer, (int)value);
  370. }
  371. }
  372. }
  373. else if (value is float || value is double)
  374. {
  375. string text = ((IFormattable) value).ToString("r", CultureInfo.InvariantCulture);
  376. if (text == "NaN" || text == "Infinity" || text == "-Infinity")
  377. {
  378. writer.Write('"');
  379. writer.Write(text);
  380. writer.Write('"');
  381. }
  382. else
  383. {
  384. writer.Write(text);
  385. }
  386. }
  387. else if (value is IMessage)
  388. {
  389. Format((IMessage)value, writer);
  390. }
  391. else
  392. {
  393. throw new ArgumentException("Unable to format value of type " + value.GetType());
  394. }
  395. }
  396. /// <summary>
  397. /// Central interception point for well-known type formatting. Any well-known types which
  398. /// don't need special handling can fall back to WriteMessage. We avoid assuming that the
  399. /// values are using the embedded well-known types, in order to allow for dynamic messages
  400. /// in the future.
  401. /// </summary>
  402. private void WriteWellKnownTypeValue(TextWriter writer, MessageDescriptor descriptor, object value)
  403. {
  404. // Currently, we can never actually get here, because null values are always handled by the caller. But if we *could*,
  405. // this would do the right thing.
  406. if (value == null)
  407. {
  408. WriteNull(writer);
  409. return;
  410. }
  411. // For wrapper types, the value will either be the (possibly boxed) "native" value,
  412. // or the message itself if we're formatting it at the top level (e.g. just calling ToString on the object itself).
  413. // If it's the message form, we can extract the value first, which *will* be the (possibly boxed) native value,
  414. // and then proceed, writing it as if we were definitely in a field. (We never need to wrap it in an extra string...
  415. // WriteValue will do the right thing.)
  416. if (descriptor.IsWrapperType)
  417. {
  418. if (value is IMessage)
  419. {
  420. var message = (IMessage) value;
  421. value = message.Descriptor.Fields[WrappersReflection.WrapperValueFieldNumber].Accessor.GetValue(message);
  422. }
  423. WriteValue(writer, value);
  424. return;
  425. }
  426. if (descriptor.FullName == Timestamp.Descriptor.FullName)
  427. {
  428. WriteTimestamp(writer, (IMessage)value);
  429. return;
  430. }
  431. if (descriptor.FullName == Duration.Descriptor.FullName)
  432. {
  433. WriteDuration(writer, (IMessage)value);
  434. return;
  435. }
  436. if (descriptor.FullName == FieldMask.Descriptor.FullName)
  437. {
  438. WriteFieldMask(writer, (IMessage)value);
  439. return;
  440. }
  441. if (descriptor.FullName == Struct.Descriptor.FullName)
  442. {
  443. WriteStruct(writer, (IMessage)value);
  444. return;
  445. }
  446. if (descriptor.FullName == ListValue.Descriptor.FullName)
  447. {
  448. var fieldAccessor = descriptor.Fields[ListValue.ValuesFieldNumber].Accessor;
  449. WriteList(writer, (IList)fieldAccessor.GetValue((IMessage)value));
  450. return;
  451. }
  452. if (descriptor.FullName == Value.Descriptor.FullName)
  453. {
  454. WriteStructFieldValue(writer, (IMessage)value);
  455. return;
  456. }
  457. if (descriptor.FullName == Any.Descriptor.FullName)
  458. {
  459. WriteAny(writer, (IMessage)value);
  460. return;
  461. }
  462. WriteMessage(writer, (IMessage)value);
  463. }
  464. private void WriteTimestamp(TextWriter writer, IMessage value)
  465. {
  466. // TODO: In the common case where this *is* using the built-in Timestamp type, we could
  467. // avoid all the reflection at this point, by casting to Timestamp. In the interests of
  468. // avoiding subtle bugs, don't do that until we've implemented DynamicMessage so that we can prove
  469. // it still works in that case.
  470. int nanos = (int) value.Descriptor.Fields[Timestamp.NanosFieldNumber].Accessor.GetValue(value);
  471. long seconds = (long) value.Descriptor.Fields[Timestamp.SecondsFieldNumber].Accessor.GetValue(value);
  472. writer.Write(Timestamp.ToJson(seconds, nanos, DiagnosticOnly));
  473. }
  474. private void WriteDuration(TextWriter writer, IMessage value)
  475. {
  476. // TODO: Same as for WriteTimestamp
  477. int nanos = (int) value.Descriptor.Fields[Duration.NanosFieldNumber].Accessor.GetValue(value);
  478. long seconds = (long) value.Descriptor.Fields[Duration.SecondsFieldNumber].Accessor.GetValue(value);
  479. writer.Write(Duration.ToJson(seconds, nanos, DiagnosticOnly));
  480. }
  481. private void WriteFieldMask(TextWriter writer, IMessage value)
  482. {
  483. var paths = (IList<string>) value.Descriptor.Fields[FieldMask.PathsFieldNumber].Accessor.GetValue(value);
  484. writer.Write(FieldMask.ToJson(paths, DiagnosticOnly));
  485. }
  486. private void WriteAny(TextWriter writer, IMessage value)
  487. {
  488. if (DiagnosticOnly)
  489. {
  490. WriteDiagnosticOnlyAny(writer, value);
  491. return;
  492. }
  493. string typeUrl = (string) value.Descriptor.Fields[Any.TypeUrlFieldNumber].Accessor.GetValue(value);
  494. ByteString data = (ByteString) value.Descriptor.Fields[Any.ValueFieldNumber].Accessor.GetValue(value);
  495. string typeName = Any.GetTypeName(typeUrl);
  496. MessageDescriptor descriptor = settings.TypeRegistry.Find(typeName);
  497. if (descriptor == null)
  498. {
  499. throw new InvalidOperationException($"Type registry has no descriptor for type name '{typeName}'");
  500. }
  501. IMessage message = descriptor.Parser.ParseFrom(data);
  502. writer.Write("{ ");
  503. WriteString(writer, AnyTypeUrlField);
  504. writer.Write(NameValueSeparator);
  505. WriteString(writer, typeUrl);
  506. if (descriptor.IsWellKnownType)
  507. {
  508. writer.Write(PropertySeparator);
  509. WriteString(writer, AnyWellKnownTypeValueField);
  510. writer.Write(NameValueSeparator);
  511. WriteWellKnownTypeValue(writer, descriptor, message);
  512. }
  513. else
  514. {
  515. WriteMessageFields(writer, message, true);
  516. }
  517. writer.Write(" }");
  518. }
  519. private void WriteDiagnosticOnlyAny(TextWriter writer, IMessage value)
  520. {
  521. string typeUrl = (string) value.Descriptor.Fields[Any.TypeUrlFieldNumber].Accessor.GetValue(value);
  522. ByteString data = (ByteString) value.Descriptor.Fields[Any.ValueFieldNumber].Accessor.GetValue(value);
  523. writer.Write("{ ");
  524. WriteString(writer, AnyTypeUrlField);
  525. writer.Write(NameValueSeparator);
  526. WriteString(writer, typeUrl);
  527. writer.Write(PropertySeparator);
  528. WriteString(writer, AnyDiagnosticValueField);
  529. writer.Write(NameValueSeparator);
  530. writer.Write('"');
  531. writer.Write(data.ToBase64());
  532. writer.Write('"');
  533. writer.Write(" }");
  534. }
  535. private void WriteStruct(TextWriter writer, IMessage message)
  536. {
  537. writer.Write("{ ");
  538. IDictionary fields = (IDictionary) message.Descriptor.Fields[Struct.FieldsFieldNumber].Accessor.GetValue(message);
  539. bool first = true;
  540. foreach (DictionaryEntry entry in fields)
  541. {
  542. string key = (string) entry.Key;
  543. IMessage value = (IMessage) entry.Value;
  544. if (string.IsNullOrEmpty(key) || value == null)
  545. {
  546. throw new InvalidOperationException("Struct fields cannot have an empty key or a null value.");
  547. }
  548. if (!first)
  549. {
  550. writer.Write(PropertySeparator);
  551. }
  552. WriteString(writer, key);
  553. writer.Write(NameValueSeparator);
  554. WriteStructFieldValue(writer, value);
  555. first = false;
  556. }
  557. writer.Write(first ? "}" : " }");
  558. }
  559. private void WriteStructFieldValue(TextWriter writer, IMessage message)
  560. {
  561. var specifiedField = message.Descriptor.Oneofs[0].Accessor.GetCaseFieldDescriptor(message);
  562. if (specifiedField == null)
  563. {
  564. throw new InvalidOperationException("Value message must contain a value for the oneof.");
  565. }
  566. object value = specifiedField.Accessor.GetValue(message);
  567. switch (specifiedField.FieldNumber)
  568. {
  569. case Value.BoolValueFieldNumber:
  570. case Value.StringValueFieldNumber:
  571. case Value.NumberValueFieldNumber:
  572. WriteValue(writer, value);
  573. return;
  574. case Value.StructValueFieldNumber:
  575. case Value.ListValueFieldNumber:
  576. // Structs and ListValues are nested messages, and already well-known types.
  577. var nestedMessage = (IMessage) specifiedField.Accessor.GetValue(message);
  578. WriteWellKnownTypeValue(writer, nestedMessage.Descriptor, nestedMessage);
  579. return;
  580. case Value.NullValueFieldNumber:
  581. WriteNull(writer);
  582. return;
  583. default:
  584. throw new InvalidOperationException("Unexpected case in struct field: " + specifiedField.FieldNumber);
  585. }
  586. }
  587. internal void WriteList(TextWriter writer, IList list)
  588. {
  589. writer.Write("[ ");
  590. bool first = true;
  591. foreach (var value in list)
  592. {
  593. if (!first)
  594. {
  595. writer.Write(PropertySeparator);
  596. }
  597. WriteValue(writer, value);
  598. first = false;
  599. }
  600. writer.Write(first ? "]" : " ]");
  601. }
  602. internal void WriteDictionary(TextWriter writer, IDictionary dictionary)
  603. {
  604. writer.Write("{ ");
  605. bool first = true;
  606. // This will box each pair. Could use IDictionaryEnumerator, but that's ugly in terms of disposal.
  607. foreach (DictionaryEntry pair in dictionary)
  608. {
  609. if (!first)
  610. {
  611. writer.Write(PropertySeparator);
  612. }
  613. string keyText;
  614. if (pair.Key is string)
  615. {
  616. keyText = (string) pair.Key;
  617. }
  618. else if (pair.Key is bool)
  619. {
  620. keyText = (bool) pair.Key ? "true" : "false";
  621. }
  622. else if (pair.Key is int || pair.Key is uint | pair.Key is long || pair.Key is ulong)
  623. {
  624. keyText = ((IFormattable) pair.Key).ToString("d", CultureInfo.InvariantCulture);
  625. }
  626. else
  627. {
  628. if (pair.Key == null)
  629. {
  630. throw new ArgumentException("Dictionary has entry with null key");
  631. }
  632. throw new ArgumentException("Unhandled dictionary key type: " + pair.Key.GetType());
  633. }
  634. WriteString(writer, keyText);
  635. writer.Write(NameValueSeparator);
  636. WriteValue(writer, pair.Value);
  637. first = false;
  638. }
  639. writer.Write(first ? "}" : " }");
  640. }
  641. /// <summary>
  642. /// Writes a string (including leading and trailing double quotes) to a builder, escaping as required.
  643. /// </summary>
  644. /// <remarks>
  645. /// Other than surrogate pair handling, this code is mostly taken from src/google/protobuf/util/internal/json_escaping.cc.
  646. /// </remarks>
  647. internal static void WriteString(TextWriter writer, string text)
  648. {
  649. writer.Write('"');
  650. for (int i = 0; i < text.Length; i++)
  651. {
  652. char c = text[i];
  653. if (c < 0xa0)
  654. {
  655. writer.Write(CommonRepresentations[c]);
  656. continue;
  657. }
  658. if (char.IsHighSurrogate(c))
  659. {
  660. // Encountered first part of a surrogate pair.
  661. // Check that we have the whole pair, and encode both parts as hex.
  662. i++;
  663. if (i == text.Length || !char.IsLowSurrogate(text[i]))
  664. {
  665. throw new ArgumentException("String contains low surrogate not followed by high surrogate");
  666. }
  667. HexEncodeUtf16CodeUnit(writer, c);
  668. HexEncodeUtf16CodeUnit(writer, text[i]);
  669. continue;
  670. }
  671. else if (char.IsLowSurrogate(c))
  672. {
  673. throw new ArgumentException("String contains high surrogate not preceded by low surrogate");
  674. }
  675. switch ((uint) c)
  676. {
  677. // These are not required by json spec
  678. // but used to prevent security bugs in javascript.
  679. case 0xfeff: // Zero width no-break space
  680. case 0xfff9: // Interlinear annotation anchor
  681. case 0xfffa: // Interlinear annotation separator
  682. case 0xfffb: // Interlinear annotation terminator
  683. case 0x00ad: // Soft-hyphen
  684. case 0x06dd: // Arabic end of ayah
  685. case 0x070f: // Syriac abbreviation mark
  686. case 0x17b4: // Khmer vowel inherent Aq
  687. case 0x17b5: // Khmer vowel inherent Aa
  688. HexEncodeUtf16CodeUnit(writer, c);
  689. break;
  690. default:
  691. if ((c >= 0x0600 && c <= 0x0603) || // Arabic signs
  692. (c >= 0x200b && c <= 0x200f) || // Zero width etc.
  693. (c >= 0x2028 && c <= 0x202e) || // Separators etc.
  694. (c >= 0x2060 && c <= 0x2064) || // Invisible etc.
  695. (c >= 0x206a && c <= 0x206f))
  696. {
  697. HexEncodeUtf16CodeUnit(writer, c);
  698. }
  699. else
  700. {
  701. // No handling of surrogates here - that's done earlier
  702. writer.Write(c);
  703. }
  704. break;
  705. }
  706. }
  707. writer.Write('"');
  708. }
  709. private const string Hex = "0123456789abcdef";
  710. private static void HexEncodeUtf16CodeUnit(TextWriter writer, char c)
  711. {
  712. writer.Write("\\u");
  713. writer.Write(Hex[(c >> 12) & 0xf]);
  714. writer.Write(Hex[(c >> 8) & 0xf]);
  715. writer.Write(Hex[(c >> 4) & 0xf]);
  716. writer.Write(Hex[(c >> 0) & 0xf]);
  717. }
  718. /// <summary>
  719. /// Settings controlling JSON formatting.
  720. /// </summary>
  721. public sealed class Settings
  722. {
  723. /// <summary>
  724. /// Default settings, as used by <see cref="JsonFormatter.Default"/>
  725. /// </summary>
  726. public static Settings Default { get; }
  727. // Workaround for the Mono compiler complaining about XML comments not being on
  728. // valid language elements.
  729. static Settings()
  730. {
  731. Default = new Settings(false);
  732. }
  733. /// <summary>
  734. /// Whether fields whose values are the default for the field type (e.g. 0 for integers)
  735. /// should be formatted (true) or omitted (false).
  736. /// </summary>
  737. public bool FormatDefaultValues { get; }
  738. /// <summary>
  739. /// The type registry used to format <see cref="Any"/> messages.
  740. /// </summary>
  741. public TypeRegistry TypeRegistry { get; }
  742. /// <summary>
  743. /// Whether to format enums as ints. Defaults to false.
  744. /// </summary>
  745. public bool FormatEnumsAsIntegers { get; }
  746. /// <summary>
  747. /// Creates a new <see cref="Settings"/> object with the specified formatting of default values
  748. /// and an empty type registry.
  749. /// </summary>
  750. /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param>
  751. public Settings(bool formatDefaultValues) : this(formatDefaultValues, TypeRegistry.Empty)
  752. {
  753. }
  754. /// <summary>
  755. /// Creates a new <see cref="Settings"/> object with the specified formatting of default values
  756. /// and type registry.
  757. /// </summary>
  758. /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param>
  759. /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages.</param>
  760. public Settings(bool formatDefaultValues, TypeRegistry typeRegistry) : this(formatDefaultValues, typeRegistry, false)
  761. {
  762. }
  763. /// <summary>
  764. /// Creates a new <see cref="Settings"/> object with the specified parameters.
  765. /// </summary>
  766. /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param>
  767. /// <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>
  768. /// <param name="formatEnumsAsIntegers"><c>true</c> to format the enums as integers; <c>false</c> to format enums as enum names.</param>
  769. private Settings(bool formatDefaultValues,
  770. TypeRegistry typeRegistry,
  771. bool formatEnumsAsIntegers)
  772. {
  773. FormatDefaultValues = formatDefaultValues;
  774. TypeRegistry = typeRegistry ?? TypeRegistry.Empty;
  775. FormatEnumsAsIntegers = formatEnumsAsIntegers;
  776. }
  777. /// <summary>
  778. /// Creates a new <see cref="Settings"/> object with the specified formatting of default values and the current settings.
  779. /// </summary>
  780. /// <param name="formatDefaultValues"><c>true</c> if default values (0, empty strings etc) should be formatted; <c>false</c> otherwise.</param>
  781. public Settings WithFormatDefaultValues(bool formatDefaultValues) => new Settings(formatDefaultValues, TypeRegistry, FormatEnumsAsIntegers);
  782. /// <summary>
  783. /// Creates a new <see cref="Settings"/> object with the specified type registry and the current settings.
  784. /// </summary>
  785. /// <param name="typeRegistry">The <see cref="TypeRegistry"/> to use when formatting <see cref="Any"/> messages.</param>
  786. public Settings WithTypeRegistry(TypeRegistry typeRegistry) => new Settings(FormatDefaultValues, typeRegistry, FormatEnumsAsIntegers);
  787. /// <summary>
  788. /// Creates a new <see cref="Settings"/> object with the specified enums formatting option and the current settings.
  789. /// </summary>
  790. /// <param name="formatEnumsAsIntegers"><c>true</c> to format the enums as integers; <c>false</c> to format enums as enum names.</param>
  791. public Settings WithFormatEnumsAsIntegers(bool formatEnumsAsIntegers) => new Settings(FormatDefaultValues, TypeRegistry, formatEnumsAsIntegers);
  792. }
  793. // Effectively a cache of mapping from enum values to the original name as specified in the proto file,
  794. // fetched by reflection.
  795. // The need for this is unfortunate, as is its unbounded size, but realistically it shouldn't cause issues.
  796. private static class OriginalEnumValueHelper
  797. {
  798. // TODO: In the future we might want to use ConcurrentDictionary, at the point where all
  799. // the platforms we target have it.
  800. private static readonly Dictionary<System.Type, Dictionary<object, string>> dictionaries
  801. = new Dictionary<System.Type, Dictionary<object, string>>();
  802. internal static string GetOriginalName(object value)
  803. {
  804. var enumType = value.GetType();
  805. Dictionary<object, string> nameMapping;
  806. lock (dictionaries)
  807. {
  808. if (!dictionaries.TryGetValue(enumType, out nameMapping))
  809. {
  810. nameMapping = GetNameMapping(enumType);
  811. dictionaries[enumType] = nameMapping;
  812. }
  813. }
  814. string originalName;
  815. // If this returns false, originalName will be null, which is what we want.
  816. nameMapping.TryGetValue(value, out originalName);
  817. return originalName;
  818. }
  819. #if NET35
  820. // TODO: Consider adding functionality to TypeExtensions to avoid this difference.
  821. private static Dictionary<object, string> GetNameMapping(System.Type enumType) =>
  822. enumType.GetFields(BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Static)
  823. .Where(f => (f.GetCustomAttributes(typeof(OriginalNameAttribute), false)
  824. .FirstOrDefault() as OriginalNameAttribute)
  825. ?.PreferredAlias ?? true)
  826. .ToDictionary(f => f.GetValue(null),
  827. f => (f.GetCustomAttributes(typeof(OriginalNameAttribute), false)
  828. .FirstOrDefault() as OriginalNameAttribute)
  829. // If the attribute hasn't been applied, fall back to the name of the field.
  830. ?.Name ?? f.Name);
  831. #else
  832. private static Dictionary<object, string> GetNameMapping(System.Type enumType) =>
  833. enumType.GetTypeInfo().DeclaredFields
  834. .Where(f => f.IsStatic)
  835. .Where(f => f.GetCustomAttributes<OriginalNameAttribute>()
  836. .FirstOrDefault()?.PreferredAlias ?? true)
  837. .ToDictionary(f => f.GetValue(null),
  838. f => f.GetCustomAttributes<OriginalNameAttribute>()
  839. .FirstOrDefault()
  840. // If the attribute hasn't been applied, fall back to the name of the field.
  841. ?.Name ?? f.Name);
  842. #endif
  843. }
  844. }
  845. }