Guest User

Untitled

a guest
Jan 16th, 2019
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.78 KB | None | 0 0
  1. public class Foo
  2. {
  3. public int Prop1;
  4. [DefaultValue("")]
  5. public string Prop2;
  6. public int? Prop3;
  7. public Bar Prop4;
  8. public Bar[] Prop5;
  9. };
  10.  
  11. public class Bar
  12. {
  13. public int Prop1;
  14. public string Prop2;
  15. public int? Prop3;
  16. };
  17.  
  18. public void NullOrEmptyStringTerminator()
  19. {
  20. var bar = new Bar { Prop1 = 0, Prop2 = "", Prop3 = 0 };
  21. var bar2 = new Bar { Prop1 = 0, Prop3 = 0 };
  22.  
  23. var inputs = new[] {
  24. new Foo{ Prop1= 1, Prop2="", Prop4= bar, Prop5 = new []{bar,bar,bar} },
  25. new Foo{ Prop1= 1, Prop4= bar, Prop5 = new []{bar2,bar2,bar2} },
  26. };
  27.  
  28. var jsonResults =
  29. inputs
  30. .Select(x =>
  31. new
  32. {
  33. Item = x,
  34. NormalSerialisation =
  35. JsonConvert.SerializeObject(
  36. x,
  37. Formatting.Indented,
  38. new JsonSerializerSettings { }
  39. ),
  40. CustomSerialisation =
  41. JsonConvert.SerializeObject(
  42. x,
  43. Formatting.Indented,
  44. new JsonSerializerSettings
  45. {
  46. NullValueHandling = NullValueHandling.Ignore,
  47. DefaultValueHandling = DefaultValueHandling.Ignore,
  48. })
  49. }
  50. ).ToList();
  51. }
  52.  
  53. using System;
  54. using System.Linq;
  55. using System.Collections.Generic;
  56. using System.ComponentModel;
  57. using Newtonsoft.Json;
  58.  
  59. public class Program
  60. {
  61. public static void Main()
  62. {
  63. var inputs = new List<object>()
  64. {new Foo{Prop2 = "" , Bar = new Bar()}};
  65. foreach (object input in inputs)
  66. {
  67. string NormalSerialisation = JsonConvert.SerializeObject(input, Formatting.Indented, new JsonSerializerSettings{});
  68. string CustomSerialisation = JsonConvert.SerializeObject(input, Formatting.Indented, new JsonSerializerSettings{NullValueHandling = NullValueHandling.Ignore, DefaultValueHandling = DefaultValueHandling.Ignore});
  69. Console.WriteLine("normal:");
  70. Console.WriteLine(NormalSerialisation);
  71. Console.WriteLine("custom:");
  72. Console.WriteLine(CustomSerialisation);
  73. }
  74. }
  75.  
  76. public class Foo
  77. {
  78.  
  79. public string Prop2
  80. {
  81. get;
  82. set;
  83. }
  84.  
  85. public Bar Bar
  86. {
  87. get;
  88. set;
  89. }
  90. }
  91.  
  92. public class Bar
  93. {
  94. [DefaultValue("")]
  95. public string Prop2;
  96. }
  97. }
  98.  
  99. normal:
  100. {
  101. "Prop2": "",
  102. "Bar": {
  103. "Prop2": null
  104. }
  105. }
  106. custom:
  107. {
  108. "Prop2": "",
  109. "Bar": {}
  110. }
Add Comment
Please, Sign In to add comment