PageRenderTime 255ms CodeModel.GetById 26ms RepoModel.GetById 1ms app.codeStats 0ms

/Rusty/Common/SimpleJson/Encode.cs

http://github.com/polyethene/IronAHK
C# | 77 lines | 67 code | 5 blank | 5 comment | 22 complexity | 52c4b597fea1c669edc804608704e1a0 MD5 | raw file
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Text;
  4. namespace IronAHK.Rusty.Common
  5. {
  6. partial class SimpleJson
  7. {
  8. /// <summary>
  9. /// Format a dictionary of string key and object value pairs as a JSON string.
  10. /// </summary>
  11. /// <param name="Elements">The table of key and values. Objects other than a string, boolean or numeric type have their <code>ToString()</code> method called for a compatible value.</param>
  12. /// <returns>A JSON representation.</returns>
  13. public static string Encode(Dictionary<string, object> Elements)
  14. {
  15. return EncodeObject(Elements);
  16. }
  17. static string EncodeObject(object node)
  18. {
  19. if (node == null)
  20. return Null;
  21. var json = new StringBuilder();
  22. if (node is Dictionary<string, object>)
  23. {
  24. var pairs = (Dictionary<string, object>)node;
  25. json.Append(ObjectOpen);
  26. int n = pairs.Keys.Count;
  27. foreach (var key in pairs.Keys)
  28. {
  29. json.Append(Space);
  30. json.Append(StringBoundary);
  31. json.Append(key);
  32. json.Append(StringBoundary);
  33. json.Append(Space);
  34. json.Append(MemberAssign);
  35. json.Append(Space);
  36. json.Append(EncodeObject(pairs[key]));
  37. n--;
  38. json.Append(n == 0 ? Space : MemberSeperator);
  39. }
  40. json.Append(ObjectClose);
  41. }
  42. else if (node is object[])
  43. {
  44. var list = (object[])node;
  45. json.Append(ArrayOpen);
  46. int n = list.Length;
  47. foreach (var sub in list)
  48. {
  49. json.Append(Space);
  50. json.Append(EncodeObject(sub));
  51. n--;
  52. json.Append(n == 0 ? Space : MemberSeperator);
  53. }
  54. json.Append(ArrayClose);
  55. }
  56. else if (node is bool)
  57. json.Append((bool)node ? True : False);
  58. else if (node is byte || node is sbyte || node is short || node is ushort || node is int || node is uint || node is long || node is ulong || node is float || node is double || node is decimal)
  59. json.Append(node.ToString());
  60. else
  61. {
  62. json.Append(StringBoundary);
  63. if (node is string)
  64. json.Append((string)node);
  65. else
  66. json.Append(node.ToString());
  67. json.Append(StringBoundary);
  68. }
  69. return json.ToString();
  70. }
  71. }
  72. }