TestExcludeIfEmpty.cs 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  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. [Obfuscation(Exclude = true, ApplyToMembers = true)]
  12. public class TestExcludeIfEmpty
  13. {
  14. class Thing
  15. {
  16. [Json("array", ExcludeIfEmpty = true)]
  17. public string[] Array;
  18. [Json("dictionary", ExcludeIfEmpty = true)]
  19. public Dictionary<string, object> Dictionary;
  20. [Json("list", ExcludeIfEmpty = true)]
  21. public List<string> List;
  22. }
  23. [Fact]
  24. public void TestDoesntWriteNull()
  25. {
  26. var thing = new Thing();
  27. // Save it
  28. var json = Json.Format(thing);
  29. // Check the object kinds were written out
  30. Assert.DoesNotContain("\"array\":", json);
  31. Assert.DoesNotContain("\"dictionary\":", json);
  32. Assert.DoesNotContain("\"list\":", json);
  33. }
  34. [Fact]
  35. public void TestDoesntWriteEmpty()
  36. {
  37. var thing = new Thing()
  38. {
  39. Array = new string[0],
  40. Dictionary = new Dictionary<string, object>(),
  41. List = new List<string>(),
  42. };
  43. // Save it
  44. var json = Json.Format(thing);
  45. // Check the object kinds were written out
  46. Assert.DoesNotContain("\"array\":", json);
  47. Assert.DoesNotContain("\"dictionary\":", json);
  48. Assert.DoesNotContain("\"list\":", json);
  49. }
  50. [Fact]
  51. public void TestDoesWriteNonEmpty()
  52. {
  53. var thing = new Thing()
  54. {
  55. Array = new string[] { "apples" },
  56. Dictionary = new Dictionary<string, object>() { { "pears", true } },
  57. List = new List<string> { "bananas" },
  58. };
  59. // Save it
  60. var json = Json.Format(thing);
  61. // Check the object kinds were written out
  62. Assert.Contains("\"array\":", json);
  63. Assert.Contains("\"dictionary\":", json);
  64. Assert.Contains("\"list\":", json);
  65. Assert.Contains("\"apples\"", json);
  66. Assert.Contains("\"pears\"", json);
  67. Assert.Contains("\"bananas\"", json);
  68. }
  69. }
  70. }