TestAbstractTypes.cs 2.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697
  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.Reflection;
  8. using Xunit;
  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. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  32. public class TestAbstractTypes
  33. {
  34. static TestAbstractTypes()
  35. {
  36. // Register a type factory that can instantiate Shape objects
  37. Json.RegisterTypeFactory(typeof(Shape), (reader, key) =>
  38. {
  39. // This method will be called back for each key in the json dictionary
  40. // until an object instance is returned
  41. // We saved the object type in a key called "kind", look for it
  42. if (key != "kind")
  43. return null;
  44. // Read the next literal (which better be a string) and instantiate the object
  45. return reader.ReadLiteral(literal =>
  46. {
  47. var className = (string)literal;
  48. if (className == typeof(Rectangle).Name)
  49. return new Rectangle();
  50. if (className == typeof(Ellipse).Name)
  51. return new Ellipse();
  52. throw new InvalidDataException(string.Format("Unknown shape kind: '{0}'", literal));
  53. });
  54. });
  55. }
  56. [Fact]
  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("\"kind\":", json);
  68. // Reload the list
  69. var shapes2 = Json.Parse<List<Shape>>(json);
  70. // Check stuff...
  71. Assert.Equal(2, shapes2.Count);
  72. Assert.IsType<Rectangle>(shapes2[0]);
  73. Assert.IsType<Ellipse>(shapes2[1]);
  74. Assert.Equal("Red", ((Rectangle)shapes2[0]).Color);
  75. Assert.Equal(10, ((Rectangle)shapes2[0]).CornerRadius);
  76. Assert.Equal("Blue", ((Ellipse)shapes2[1]).Color);
  77. Assert.True(((Ellipse)shapes2[1]).Filled);
  78. }
  79. }
  80. }