Formatter.cs 2.2 KB

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