TestCustomFormat.cs 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using PetaTest;
  6. using PetaJson;
  7. using System.IO;
  8. using System.Globalization;
  9. namespace TestCases
  10. {
  11. struct Point
  12. {
  13. public int X;
  14. public int Y;
  15. }
  16. [TestFixture]
  17. public class TestCustomFormat
  18. {
  19. static TestCustomFormat()
  20. {
  21. // Custom formatter
  22. Json.RegisterFormatter<Point>( (writer,point) =>
  23. {
  24. writer.WriteStringLiteral(string.Format("{0},{1}", point.X, point.Y));
  25. });
  26. // Custom parser
  27. Json.RegisterParser<Point>( literal => {
  28. var parts = ((string)literal).Split(',');
  29. if (parts.Length!=2)
  30. throw new InvalidDataException("Badly formatted point");
  31. return new Point()
  32. {
  33. X = int.Parse(parts[0], CultureInfo.InvariantCulture),
  34. Y = int.Parse(parts[0], CultureInfo.InvariantCulture),
  35. };
  36. });
  37. }
  38. [Test]
  39. public void Test()
  40. {
  41. var p = new Point() { X = 10, Y = 20 };
  42. var json = Json.Format(p);
  43. Assert.AreEqual(json, "\"10,20\"");
  44. var p2 = Json.Parse<Point>(json);
  45. Assert.Equals(p.X, p2.X);
  46. Assert.Equals(p.Y, p2.Y);
  47. }
  48. [Test]
  49. public void TestExceptionPassed()
  50. {
  51. Assert.Throws<JsonParseException>(() => Json.Parse<Point>("\"10,20,30\""));
  52. }
  53. }
  54. }