TestCustomFormat.cs 1.7 KB

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