Trivial JSON example, serialization and deserialization


/ Published in: C#
Save to your folder(s)



Copy this code and paste it in your HTML
  1. // Purpose of this code: to test and understand JSON usage in C#.
  2. // What it does:
  3. // Defines a datatype that is nested, with an array and enum
  4. // Creates and initializes and object
  5. // Converts to JSON string and back into a 2nd object and deep-equals the two (should be the same).
  6. // modifies the JSON string (only formatting) and converts back into a 3rd object and compares (should be the same).
  7. // modifies the data in the JSON string and converts back into a 4th object and compares (should be different).
  8. // Creates a totally different string with the same data as the initial object. Converts string to object. (should be the same).
  9.  
  10. #region Declare a type that: [1] is nested, [2] has an enum, [3] has an array.
  11. public enum EmpType // example enum
  12. {
  13. salaried,
  14. hourly,
  15. contract,
  16. };
  17.  
  18. public class MyEmployee
  19. {
  20. public string name { get; set; }
  21. public string id { get; set; }
  22. public int age { get; set; }
  23. public bool ok { get; set; }
  24. public EmpType empType { get; set; }
  25. }
  26.  
  27. public class MyTopLevel
  28. {
  29. public string s { get; set; }
  30. public List<MyEmployee> list;
  31. public int i { get; set; }
  32.  
  33. // Equals effectively performs a deep equals with a slight chance of returning a false equals.
  34. public bool Equals(MyTopLevel that)
  35. {
  36. // Note, there's a one in 4,294,967,295 chance that this will provide a false equals
  37. // http://mikehadlow.blogspot.com/2006/11/using-memorystream-and-binaryformatter.html
  38. return this.GetHashCode() == that.GetHashCode();
  39. }
  40.  
  41. }
  42.  
  43. #endregion
  44.  
  45.  
  46. // Allocate and initialize data
  47. MyTopLevel myObj_1 = new MyTopLevel
  48. {
  49. s = "asdf",
  50. list = new List<MyEmployee>()
  51. {
  52. new MyEmployee { name = "aaa", id = "111" , age = 30, ok=true , empType=EmpType.contract },
  53. new MyEmployee { name = "bbb", id = "Cohen", age = 31, ok=false, empType=EmpType.hourly },
  54. new MyEmployee { name = "ccc", id = "Biton", age = 20, ok=true , empType=EmpType.salaried },
  55. },
  56. i = 1234
  57. };
  58.  
  59. DataContractJsonSerializer serializer = new DataContractJsonSerializer(myObj_1.GetType());
  60.  
  61. #region Serialize
  62.  
  63. MemoryStream ms1 = new MemoryStream();
  64. serializer.WriteObject(ms1, myObj_1);
  65. string str = Encoding.Default.GetString(ms1.ToArray());
  66.  
  67. MessageBox.Show(str);
  68.  
  69. #endregion
  70.  
  71. #region Deserialization
  72.  
  73. string str2 = str.Replace(",", ",\n");// This will change the formatting of the string without changing the data.
  74.  
  75. MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(str2));
  76. MyTopLevel myObj_2 = serializer.ReadObject(ms) as MyTopLevel;
  77. ms.Close();
  78.  
  79. // Test the reconstituted object - it should be deep-equal to the first object.
  80. System.Diagnostics.Debug.Assert(myObj_1.Equals(myObj_2));
  81.  
  82. #endregion
  83.  
  84. #region Test !Equals using an object created from modified data string
  85.  
  86. str = str.Replace("aaa", "aa"); // change an element of the serialized data to test .Equals().
  87.  
  88. ms = new MemoryStream(Encoding.Unicode.GetBytes(str));
  89. MyTopLevel myObj_3 = serializer.ReadObject(ms) as MyTopLevel;
  90. ms.Close();
  91.  
  92. // Test the reconstitued object. It should not be deep-equal to the first object because of the str.Replace().
  93. System.Diagnostics.Debug.Assert(!myObj_1.Equals(myObj_3));
  94.  
  95. #endregion
  96.  
  97. // Generate a string expecting to create an object identical (deep equal) to the first object.
  98. // Omit empType 0 expecting it to result in the default of zero.
  99. // Add indentation and white spaces.
  100. str =
  101. "{" +
  102. " \"i\":1234,\n" +
  103. " \"list\":\n" +
  104. " [\n" +
  105. " {\"age\":30, \"empType\":2, \"id\":\"111\", \"name\":\"aaa\", \"ok\":true },\n" +
  106. " {\"age\":31, \"empType\":1, \"id\":\"Cohen\", \"name\":\"bbb\", \"ok\":false},\n" +
  107. " {\"age\":20, \"id\":\"Biton\", \"name\":\"ccc\", \"ok\":true }\n" +
  108. " ],\n" +
  109. " \"s\":\"asdf\"\n" +
  110. "}\n";
  111.  
  112. MessageBox.Show(str);
  113.  
  114. ms = new MemoryStream(Encoding.Unicode.GetBytes(str));
  115. MyTopLevel myObj_4 = serializer.ReadObject(ms) as MyTopLevel;
  116. ms.Close();
  117.  
  118. // Test the reconstitued object. It should not be deep-equal to the first object because of the str.Replace().
  119. System.Diagnostics.Debug.Assert(!myObj_1.Equals(myObj_4));

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.