Advertisement
Guest User

Untitled

a guest
Oct 19th, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.91 KB | None | 0 0
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5.  
  6. namespace Luminous.Tools
  7. {
  8. /// <summary>
  9. /// A utility to format JSON in pretty text.
  10. /// </summary>
  11. public static class JsonFormatter
  12. {
  13. private const string INDENT_STRING = " ";
  14.  
  15. /// <summary>
  16. /// Format the JSON to pretty text.
  17. /// </summary>
  18. /// <param name="str"></param>
  19. /// <returns></returns>
  20. public static string FormatJson(string str)
  21. {
  22. if (string.IsNullOrEmpty(str))
  23. {
  24. Console.WriteLine($"Passed string: {str} was null or empty. Cannot format. Returning empty string.");
  25. return string.Empty;
  26. }
  27. var indent = 0;
  28. var quoted = false;
  29. var sb = new StringBuilder();
  30. for (var i = 0; i < str.Length; i++)
  31. {
  32. var ch = str[i];
  33. switch (ch)
  34. {
  35. case '{':
  36. case '[':
  37. sb.Append(ch);
  38. if (!quoted)
  39. {
  40. sb.AppendLine();
  41. Enumerable.Range(0, ++indent).ForEach(item => sb.Append(INDENT_STRING));
  42. }
  43.  
  44. break;
  45. case '}':
  46. case ']':
  47. if (!quoted)
  48. {
  49. sb.AppendLine();
  50. Enumerable.Range(0, --indent).ForEach(item => sb.Append(INDENT_STRING));
  51. }
  52.  
  53. sb.Append(ch);
  54. break;
  55. case '"':
  56. sb.Append(ch);
  57. bool escaped = false;
  58. var index = i;
  59. while (index > 0 && str[--index] == '\\')
  60. escaped = !escaped;
  61. if (!escaped)
  62. quoted = !quoted;
  63. break;
  64. case ',':
  65. sb.Append(ch);
  66. if (!quoted)
  67. {
  68. sb.AppendLine();
  69. Enumerable.Range(0, indent).ForEach(item => sb.Append(INDENT_STRING));
  70. }
  71.  
  72. break;
  73. case ':':
  74. sb.Append(ch);
  75. if (!quoted)
  76. sb.Append(" ");
  77. break;
  78. default:
  79. sb.Append(ch);
  80. break;
  81. }
  82. }
  83.  
  84. return sb.ToString();
  85. }
  86. }
  87.  
  88. static class Extensions
  89. {
  90. public static void ForEach<T>(this IEnumerable<T> ie, Action<T> action)
  91. {
  92. foreach (var i in ie)
  93. {
  94. action(i);
  95. }
  96. }
  97. }
  98. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement