JsonFormatter.cs 38 KB

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