TestAbstractTypes.cs 2.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using System.Text;
  5. using PetaJson;
  6. using PetaTest;
  7. using System.IO;
  8. namespace TestCases
  9. {
  10. abstract class Shape : IJsonWriting
  11. {
  12. [Json] public string Color;
  13. // Override OnJsonWriting to write out the derived class type
  14. void IJsonWriting.OnJsonWriting(IJsonWriter w)
  15. {
  16. w.WriteKey("kind");
  17. w.WriteStringLiteral(GetType().Name);
  18. }
  19. }
  20. class Rectangle : Shape
  21. {
  22. [Json]
  23. public float CornerRadius;
  24. }
  25. class Ellipse : Shape
  26. {
  27. [Json]
  28. public bool Filled;
  29. }
  30. [TestFixture]
  31. class TestAbstractTypes
  32. {
  33. static TestAbstractTypes()
  34. {
  35. // Register a type factory that can instantiate Shape objects
  36. Json.RegisterTypeFactory(typeof(Shape), (reader, key) =>
  37. {
  38. // This method will be called back for each key in the json dictionary
  39. // until an object instance is returned
  40. // We saved the object type in a key called "kind", look for it
  41. if (key != "kind")
  42. return null;
  43. // Read the next literal (which better be a string) and instantiate the object
  44. return reader.ReadLiteral(literal =>
  45. {
  46. switch ((string)literal)
  47. {
  48. case "Rectangle": return new Rectangle();
  49. case "Ellipse": return new Ellipse();
  50. default:
  51. throw new InvalidDataException(string.Format("Unknown shape kind: '{0}'", literal));
  52. }
  53. });
  54. });
  55. }
  56. [Test]
  57. public void Test()
  58. {
  59. // Create a list of shapes
  60. var shapes = new List<Shape>();
  61. shapes.Add(new Rectangle() { Color = "Red", CornerRadius = 10 });
  62. shapes.Add(new Ellipse() { Color="Blue", Filled = true });
  63. // Save it
  64. var json = Json.Format(shapes);
  65. Console.WriteLine(json);
  66. // Check the object kinds were written out
  67. Assert.Contains(json, "\"kind\": \"Rectangle\"");
  68. Assert.Contains(json, "\"kind\": \"Ellipse\"");
  69. // Reload the list
  70. var shapes2 = Json.Parse<List<Shape>>(json);
  71. // Check stuff...
  72. Assert.AreEqual(shapes2.Count, 2);
  73. Assert.IsInstanceOf<Rectangle>(shapes2[0]);
  74. Assert.IsInstanceOf<Ellipse>(shapes2[1]);
  75. Assert.AreEqual(((Rectangle)shapes2[0]).Color, "Red");
  76. Assert.AreEqual(((Rectangle)shapes2[0]).CornerRadius, 10);
  77. Assert.AreEqual(((Ellipse)shapes2[1]).Color, "Blue");
  78. Assert.AreEqual(((Ellipse)shapes2[1]).Filled, true);
  79. }
  80. }
  81. }