JsonFormatter.cs 37 KB

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