Return to Snippet

Revision: 21077
at December 3, 2009 12:40 by jimfred


Updated Code
// Purpose of this code: to test and understand JSON usage in C#.
// What it does:
//   Defines a datatype that is nested, with an array and enum
//   Creates and initializes and object
//   Converts to JSON string and back into a 2nd object and deep-equals the two (should be the same).
//   modifies the JSON string (only formatting) and converts back into a 3rd object and compares (should be the same).
//   modifies the data in the JSON string and converts back into a 4th object and compares (should be different).
//   Creates a totally different string with the same data as the initial object. Converts string to object. (should be the same).

#region Declare a type that: [1] is nested, [2] has an enum, [3] has an array.
         public enum EmpType // example enum
         {
            salaried,
            hourly,
            contract,
         };

         public class MyEmployee
         {
            public string  name    { get; set; }
            public string  id      { get; set; }
            public int     age     { get; set; }
            public bool    ok      { get; set; }
            public EmpType empType { get; set; }
         }

         public class MyTopLevel
         {
            public string  s      { get; set; }
            public List<MyEmployee> list;
            public int     i     { get; set; }

            // Equals effectively performs a deep equals with a slight chance of returning a false equals. 
            public bool Equals(MyTopLevel that)
            {
               // Note, there's a one in 4,294,967,295 chance that this will provide a false equals
               // http://mikehadlow.blogspot.com/2006/11/using-memorystream-and-binaryformatter.html
               return this.GetHashCode() == that.GetHashCode();
            }

         }

      #endregion


         // Allocate and initialize data
         MyTopLevel myObj_1 = new MyTopLevel
         {
            s = "asdf",
            list = new List<MyEmployee>()
            { 
               new MyEmployee { name = "aaa", id = "111"  , age = 30, ok=true , empType=EmpType.contract }, 
               new MyEmployee { name = "bbb", id = "Cohen", age = 31, ok=false, empType=EmpType.hourly   }, 
               new MyEmployee { name = "ccc", id = "Biton", age = 20, ok=true , empType=EmpType.salaried }, 
            },
            i = 1234
         };

         DataContractJsonSerializer serializer = new DataContractJsonSerializer(myObj_1.GetType());

         #region Serialize

         MemoryStream ms1 = new MemoryStream();
         serializer.WriteObject(ms1, myObj_1);
         string str = Encoding.Default.GetString(ms1.ToArray());

         MessageBox.Show(str);

         #endregion
         
         #region Deserialization

         string str2 = str.Replace(",", ",\n");// This will change the formatting of the string without changing the data.
      
         MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(str2));
         MyTopLevel myObj_2 = serializer.ReadObject(ms) as MyTopLevel;
         ms.Close();

         // Test the reconstituted object - it should be deep-equal to the first object.   
         System.Diagnostics.Debug.Assert(myObj_1.Equals(myObj_2));

         #endregion

         #region Test !Equals using an object created from modified data string

         str = str.Replace("aaa", "aa"); // change an element of the serialized data to test .Equals().

         ms = new MemoryStream(Encoding.Unicode.GetBytes(str));
         MyTopLevel myObj_3 = serializer.ReadObject(ms) as MyTopLevel;
         ms.Close();

         // Test the reconstitued object. It should not be deep-equal to the first object because of the str.Replace().   
         System.Diagnostics.Debug.Assert(!myObj_1.Equals(myObj_3));

         #endregion

         // Generate a string expecting to create an object identical (deep equal) to the first object.
         // Omit empType 0 expecting it to result in the default of zero.
         // Add indentation and white spaces.
         str =
            "{" +
            "   \"i\":1234,\n" +
            "   \"list\":\n" +
            "   [\n" +
            "      {\"age\":30, \"empType\":2, \"id\":\"111\",   \"name\":\"aaa\", \"ok\":true },\n" +
            "      {\"age\":31, \"empType\":1, \"id\":\"Cohen\", \"name\":\"bbb\", \"ok\":false},\n" +
            "      {\"age\":20,                \"id\":\"Biton\", \"name\":\"ccc\", \"ok\":true }\n" +
            "   ],\n" +
            "   \"s\":\"asdf\"\n" +
            "}\n";

         MessageBox.Show(str);

         ms = new MemoryStream(Encoding.Unicode.GetBytes(str));
         MyTopLevel myObj_4 = serializer.ReadObject(ms) as MyTopLevel;
         ms.Close();

         // Test the reconstitued object. It should not be deep-equal to the first object because of the str.Replace().   
         System.Diagnostics.Debug.Assert(!myObj_1.Equals(myObj_4));

Revision: 21076
at December 3, 2009 12:40 by jimfred


Updated Code
// Purpose of this code: to test and understand JSON usage in C#.
      // What it does:
      //   Defines a datatype that is nested, with an array and enum
      //   Creates and initializes and object
      //   Converts to JSON string and back into a 2nd object and deep-equals the two (should be the same).
      //   modifies the JSON string (only formatting) and converts back into a 3rd object and compares (should be the same).
      //   modifies the data in the JSON string and converts back into a 4th object and compares (should be different).
      //   Creates a totally different string with the same data as the initial object. Converts string to object. (should be the same).

#region Declare a type that: [1] is nested, [2] has an enum, [3] has an array.
         public enum EmpType // example enum
         {
            salaried,
            hourly,
            contract,
         };

         public class MyEmployee
         {
            public string  name    { get; set; }
            public string  id      { get; set; }
            public int     age     { get; set; }
            public bool    ok      { get; set; }
            public EmpType empType { get; set; }
         }

         public class MyTopLevel
         {
            public string  s      { get; set; }
            public List<MyEmployee> list;
            public int     i     { get; set; }

            // Equals effectively performs a deep equals with a slight chance of returning a false equals. 
            public bool Equals(MyTopLevel that)
            {
               // Note, there's a one in 4,294,967,295 chance that this will provide a false equals
               // http://mikehadlow.blogspot.com/2006/11/using-memorystream-and-binaryformatter.html
               return this.GetHashCode() == that.GetHashCode();
            }

         }

      #endregion


         // Allocate and initialize data
         MyTopLevel myObj_1 = new MyTopLevel
         {
            s = "asdf",
            list = new List<MyEmployee>()
            { 
               new MyEmployee { name = "aaa", id = "111"  , age = 30, ok=true , empType=EmpType.contract }, 
               new MyEmployee { name = "bbb", id = "Cohen", age = 31, ok=false, empType=EmpType.hourly   }, 
               new MyEmployee { name = "ccc", id = "Biton", age = 20, ok=true , empType=EmpType.salaried }, 
            },
            i = 1234
         };

         DataContractJsonSerializer serializer = new DataContractJsonSerializer(myObj_1.GetType());

         #region Serialize

         MemoryStream ms1 = new MemoryStream();
         serializer.WriteObject(ms1, myObj_1);
         string str = Encoding.Default.GetString(ms1.ToArray());

         MessageBox.Show(str);

         #endregion
         
         #region Deserialization

         string str2 = str.Replace(",", ",\n");// This will change the formatting of the string without changing the data.
      
         MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(str2));
         MyTopLevel myObj_2 = serializer.ReadObject(ms) as MyTopLevel;
         ms.Close();

         // Test the reconstituted object - it should be deep-equal to the first object.   
         System.Diagnostics.Debug.Assert(myObj_1.Equals(myObj_2));

         #endregion

         #region Test !Equals using an object created from modified data string

         str = str.Replace("aaa", "aa"); // change an element of the serialized data to test .Equals().

         ms = new MemoryStream(Encoding.Unicode.GetBytes(str));
         MyTopLevel myObj_3 = serializer.ReadObject(ms) as MyTopLevel;
         ms.Close();

         // Test the reconstitued object. It should not be deep-equal to the first object because of the str.Replace().   
         System.Diagnostics.Debug.Assert(!myObj_1.Equals(myObj_3));

         #endregion

         // Generate a string expecting to create an object identical (deep equal) to the first object.
         // Omit empType 0 expecting it to result in the default of zero.
         // Add indentation and white spaces.
         str =
            "{" +
            "   \"i\":1234,\n" +
            "   \"list\":\n" +
            "   [\n" +
            "      {\"age\":30, \"empType\":2, \"id\":\"111\",   \"name\":\"aaa\", \"ok\":true },\n" +
            "      {\"age\":31, \"empType\":1, \"id\":\"Cohen\", \"name\":\"bbb\", \"ok\":false},\n" +
            "      {\"age\":20,                \"id\":\"Biton\", \"name\":\"ccc\", \"ok\":true }\n" +
            "   ],\n" +
            "   \"s\":\"asdf\"\n" +
            "}\n";

         MessageBox.Show(str);

         ms = new MemoryStream(Encoding.Unicode.GetBytes(str));
         MyTopLevel myObj_4 = serializer.ReadObject(ms) as MyTopLevel;
         ms.Close();

         // Test the reconstitued object. It should not be deep-equal to the first object because of the str.Replace().   
         System.Diagnostics.Debug.Assert(!myObj_1.Equals(myObj_4));

Revision: 21075
at December 3, 2009 12:26 by jimfred


Updated Code
#region Declare a type that: [1] is nested, [2] has an enum, [3] has an array.
         public enum EmpType // example enum
         {
            salaried,
            hourly,
            contract,
         };

         public class MyEmployee
         {
            public string  name    { get; set; }
            public string  id      { get; set; }
            public int     age     { get; set; }
            public bool    ok      { get; set; }
            public EmpType empType { get; set; }
         }

         public class MyTopLevel
         {
            public string  s      { get; set; }
            public List<MyEmployee> list;
            public int     i     { get; set; }

            // Equals effectively performs a deep equals with a slight chance of returning a false equals. 
            public bool Equals(MyTopLevel that)
            {
               // Note, there's a one in 4,294,967,295 chance that this will provide a false equals
               // http://mikehadlow.blogspot.com/2006/11/using-memorystream-and-binaryformatter.html
               return this.GetHashCode() == that.GetHashCode();
            }

         }

      #endregion


         // Allocate and initialize data
         MyTopLevel myObj_1 = new MyTopLevel
         {
            s = "asdf",
            list = new List<MyEmployee>()
            { 
               new MyEmployee { name = "aaa", id = "111"  , age = 30, ok=true , empType=EmpType.contract }, 
               new MyEmployee { name = "bbb", id = "Cohen", age = 31, ok=false, empType=EmpType.hourly   }, 
               new MyEmployee { name = "ccc", id = "Biton", age = 20, ok=true , empType=EmpType.salaried }, 
            },
            i = 1234
         };

         DataContractJsonSerializer serializer = new DataContractJsonSerializer(myObj_1.GetType());

         #region Serialize

         MemoryStream ms1 = new MemoryStream();
         serializer.WriteObject(ms1, myObj_1);
         string str = Encoding.Default.GetString(ms1.ToArray());

         MessageBox.Show(str);

         #endregion
         
         #region Deserialization

         string str2 = str.Replace(",", ",\n");// This will change the formatting of the string without changing the data.
      
         MemoryStream ms = new MemoryStream(Encoding.Unicode.GetBytes(str2));
         MyTopLevel myObj_2 = serializer.ReadObject(ms) as MyTopLevel;
         ms.Close();

         // Test the reconstituted object - it should be deep-equal to the first object.   
         System.Diagnostics.Debug.Assert(myObj_1.Equals(myObj_2));

         #endregion

         #region Test !Equals using an object created from modified data string

         str = str.Replace("aaa", "aa"); // change an element of the serialized data to test .Equals().

         ms = new MemoryStream(Encoding.Unicode.GetBytes(str));
         MyTopLevel myObj_3 = serializer.ReadObject(ms) as MyTopLevel;
         ms.Close();

         // Test the reconstitued object. It should not be deep-equal to the first object because of the str.Replace().   
         System.Diagnostics.Debug.Assert(!myObj_1.Equals(myObj_3));

         #endregion

         // Generate a string expecting to create an object identical (deep equal) to the first object.
         // Omit empType 0 expecting it to result in the default of zero.
         // Add indentation and white spaces.
         str =
            "{" +
            "   \"i\":1234,\n" +
            "   \"list\":\n" +
            "   [\n" +
            "      {\"age\":30, \"empType\":2, \"id\":\"111\",   \"name\":\"aaa\", \"ok\":true },\n" +
            "      {\"age\":31, \"empType\":1, \"id\":\"Cohen\", \"name\":\"bbb\", \"ok\":false},\n" +
            "      {\"age\":20,                \"id\":\"Biton\", \"name\":\"ccc\", \"ok\":true }\n" +
            "   ],\n" +
            "   \"s\":\"asdf\"\n" +
            "}\n";

         MessageBox.Show(str);

         ms = new MemoryStream(Encoding.Unicode.GetBytes(str));
         MyTopLevel myObj_4 = serializer.ReadObject(ms) as MyTopLevel;
         ms.Close();

         // Test the reconstitued object. It should not be deep-equal to the first object because of the str.Replace().   
         System.Diagnostics.Debug.Assert(!myObj_1.Equals(myObj_4));

Revision: 21074
at December 2, 2009 18:34 by jimfred


Initial Code
// Added
using System.ServiceModel.Web;           // for DataContractJsonSerializer. Need reference too.
using System.Runtime.Serialization.Json; // for DataContractJsonSerializer

// Create a test data type.
public enum EmpType // example enum
{
   salaried,
   hourly,
   contract,
};

public class Employee
{
 public string  name    { get; set; }
 public string  id      { get; set; }
 public int     age     { get; set; }
 public bool    ok      { get; set; }
 public EmpType empType { get; set; }
}

// Allocate data
List<Employee> myObject = new List<Employee>()
{ 
	new Employee { name = "aaa", id = "111"  , age = 30, ok=true , empType=EmpType.contract }, 
	new Employee { name = "bbb", id = "Cohen", age = 31, ok=false, empType=EmpType.hourly   }, 
	new Employee { name = "ccc", id = "Biton", age = 20, ok=true , empType=EmpType.salaried }, 
};

DataContractJsonSerializer serializer = new DataContractJsonSerializer(myObject.GetType());

// Serialize
MemoryStream ms = new MemoryStream();
serializer.WriteObject(ms, myObject);
string str = Encoding.Default.GetString(ms.ToArray());
MessageBox.Show(str);

// Deserialization
ms = new MemoryStream(Encoding.Unicode.GetBytes(str));
List<Employee> myObject2 = serializer.ReadObject(ms) as List<Employee>;
ms.Close();

// myObject2 same as myObject.

Initial URL

                                

Initial Description

                                

Initial Title
Trivial  JSON example, serialization and deserialization

Initial Tags

                                

Initial Language
C#