TestCustomFormat.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using Topten.JsonKit;
  6. using System.IO;
  7. using System.Globalization;
  8. using System.Reflection;
  9. using Xunit;
  10. namespace TestCases
  11. {
  12. struct PointSimple
  13. {
  14. public int X;
  15. public int Y;
  16. private string FormatJson()
  17. {
  18. return string.Format("{0},{1}", X, Y);
  19. }
  20. private static PointSimple ParseJson(string literal)
  21. {
  22. var parts = literal.Split(',');
  23. if (parts.Length == 2)
  24. {
  25. return new PointSimple()
  26. {
  27. X = int.Parse(parts[0], CultureInfo.InvariantCulture),
  28. Y = int.Parse(parts[1], CultureInfo.InvariantCulture),
  29. };
  30. }
  31. throw new InvalidDataException("Invalid point");
  32. }
  33. }
  34. struct PointComplex
  35. {
  36. public int X;
  37. public int Y;
  38. private void FormatJson(IJsonWriter writer)
  39. {
  40. writer.WriteStringLiteral(string.Format("{0},{1}", X, Y));
  41. }
  42. private static PointComplex ParseJson(IJsonReader r)
  43. {
  44. if (r.GetLiteralKind() == LiteralKind.String)
  45. {
  46. var parts = ((string)r.GetLiteralString()).Split(',');
  47. if (parts.Length == 2)
  48. {
  49. var pt = new PointComplex()
  50. {
  51. X = int.Parse(parts[0], CultureInfo.InvariantCulture),
  52. Y = int.Parse(parts[1], CultureInfo.InvariantCulture),
  53. };
  54. r.NextToken();
  55. return pt;
  56. }
  57. }
  58. throw new InvalidDataException("Invalid point");
  59. }
  60. }
  61. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  62. public class TestCustomFormat
  63. {
  64. [Fact]
  65. public void TestSimple()
  66. {
  67. var p = new PointSimple() { X = 10, Y = 20 };
  68. var json = Json.Format(p);
  69. Assert.Equal("\"10,20\"", json);
  70. var p2 = Json.Parse<PointSimple>(json);
  71. Assert.Equal(p.X, p2.X);
  72. Assert.Equal(p.Y, p2.Y);
  73. }
  74. [Fact]
  75. public void TestSimpleExceptionPassed()
  76. {
  77. Assert.Throws<JsonParseException>(() => Json.Parse<PointSimple>("\"10,20,30\""));
  78. }
  79. [Fact]
  80. public void TestComplex()
  81. {
  82. var p = new PointComplex() { X = 10, Y = 20 };
  83. var json = Json.Format(p);
  84. Assert.Equal("\"10,20\"", json);
  85. var p2 = Json.Parse<PointComplex>(json);
  86. Assert.Equal(p.X, p2.X);
  87. Assert.Equal(p.Y, p2.Y);
  88. }
  89. [Fact]
  90. public void TestComplexExceptionPassed()
  91. {
  92. Assert.Throws<JsonParseException>(() => Json.Parse<PointComplex>("\"10,20,30\""));
  93. }
  94. }
  95. }