JsonFormatter.cs 36 KB

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