TestAbstractTypes.cs 3.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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. using System.Reflection;
  9. namespace TestCases
  10. {
  11. abstract class Shape : IJsonWriting
  12. {
  13. [Json("color")] public string Color;
  14. // Override OnJsonWriting to write out the derived class type
  15. void IJsonWriting.OnJsonWriting(IJsonWriter w)
  16. {
  17. w.WriteKey("kind");
  18. w.WriteStringLiteral(GetType().Name);
  19. }
  20. }
  21. class Rectangle : Shape
  22. {
  23. [Json("cornerRadius")]
  24. public float CornerRadius;
  25. }
  26. class Ellipse : Shape
  27. {
  28. [Json("filled")]
  29. public bool Filled;
  30. }
  31. [TestFixture]
  32. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  33. class TestAbstractTypes
  34. {
  35. static TestAbstractTypes()
  36. {
  37. // Register a type factory that can instantiate Shape objects
  38. Json.RegisterTypeFactory(typeof(Shape), (reader, key) =>
  39. {
  40. // This method will be called back for each key in the json dictionary
  41. // until an object instance is returned
  42. // We saved the object type in a key called "kind", look for it
  43. if (key != "kind")
  44. return null;
  45. // Read the next literal (which better be a string) and instantiate the object
  46. return reader.ReadLiteral(literal =>
  47. {
  48. var className = (string)literal;
  49. if (className == typeof(Rectangle).Name)
  50. return new Rectangle();
  51. if (className == typeof(Ellipse).Name)
  52. return new Ellipse();
  53. throw new InvalidDataException(string.Format("Unknown shape kind: '{0}'", literal));
  54. });
  55. });
  56. }
  57. [Test]
  58. public void Test()
  59. {
  60. // Create a list of shapes
  61. var shapes = new List<Shape>();
  62. shapes.Add(new Rectangle() { Color = "Red", CornerRadius = 10 });
  63. shapes.Add(new Ellipse() { Color="Blue", Filled = true });
  64. // Save it
  65. var json = Json.Format(shapes);
  66. Console.WriteLine(json);
  67. // Check the object kinds were written out
  68. Assert.Contains(json, "\"kind\":");
  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. }