Formatter.cs 2.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. using System.Collections.Generic;
  2. using System.Text;
  3. namespace FastJSON
  4. {
  5. internal static class Formatter
  6. {
  7. public static string Indent = " ";
  8. public static void AppendIndent(StringBuilder sb, int count)
  9. {
  10. for (; count > 0; --count) sb.Append(Indent);
  11. }
  12. public static string PrettyPrint(string input)
  13. {
  14. var output = new StringBuilder();
  15. int depth = 0;
  16. int len = input.Length;
  17. char[] chars = input.ToCharArray();
  18. for (int i = 0; i < len; ++i)
  19. {
  20. char ch = chars[i];
  21. if (ch == '\"') // found string span
  22. {
  23. bool str = true;
  24. while (str)
  25. {
  26. output.Append(ch);
  27. ch = chars[++i];
  28. if (ch == '\\')
  29. {
  30. output.Append(ch);
  31. ch = chars[++i];
  32. }
  33. else if (ch == '\"')
  34. str = false;
  35. }
  36. }
  37. switch (ch)
  38. {
  39. case '{':
  40. case '[':
  41. output.Append(ch);
  42. output.AppendLine();
  43. AppendIndent(output, ++depth);
  44. break;
  45. case '}':
  46. case ']':
  47. output.AppendLine();
  48. AppendIndent(output, --depth);
  49. output.Append(ch);
  50. break;
  51. case ',':
  52. output.Append(ch);
  53. output.AppendLine();
  54. AppendIndent(output, depth);
  55. break;
  56. case ':':
  57. output.Append(" : ");
  58. break;
  59. default:
  60. if (!char.IsWhiteSpace(ch))
  61. output.Append(ch);
  62. break;
  63. }
  64. }
  65. return output.ToString();
  66. }
  67. }
  68. }