@manhng

Welcome to my blog!

.NET 3.5 JSON Serializing and Deserializing

November 12, 2019 14:32

.NET 3.5 Serializing and Deserializing (edit)

https://www.nuget.org/packages/Newtonsoft.Json/3.5.8

https://pietschsoft.com/post/2008/02/28/net-35-json-serialization-using-the-datacontractjsonserializer

https://www.codeguru.com/csharp/.net/net_data/serializing-and-deserializing-xml-in-.net.html

    public class JsonSerializerClass
    {
        public static string Serialize(T obj)
        {
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            serializer.WriteObject(ms, obj);
            string retVal = System.Text.Encoding.Default.GetString(ms.ToArray());
            ms.Dispose();
            return retVal;
        }

        public static T Deserialize(string json)
        {
            T obj = System.Activator.CreateInstance();
            System.IO.MemoryStream ms = new System.IO.MemoryStream(System.Text.Encoding.Unicode.GetBytes(json));
            System.Runtime.Serialization.Json.DataContractJsonSerializer serializer = new System.Runtime.Serialization.Json.DataContractJsonSerializer(obj.GetType());
            obj = (T)serializer.ReadObject(ms);
            ms.Close();
            ms.Dispose();
            return obj;
        }
    }

    /// 
    /// TODO: MANH - Write string to .txt file in your Desktop folder
    /// 
    public static class Utils
    {
        public static void WriteLog(string msg)
        {
            try
            {
                //Path log folder
                string folder = GetDesktopFolder();

                //Path log file
                string path = folder + "\\Test.log";

                // This text is added only once to the file.
                if (!File.Exists(path))
                {
                    // Create a file to write to.
                    using (StreamWriter sw = File.CreateText(path))
                    {
                        sw.WriteLine(msg);
                    }
                }

                // This text is always added, making the file longer over time
                // if it is not deleted.
                using (StreamWriter sw = File.AppendText(path))
                {
                    sw.WriteLine(msg);
                }
            }
            catch (Exception e)
            {
                Debug.WriteLine("Exception: " + e.ToString());
            }
            finally
            {
                Debug.WriteLine("Executing finally block.");
            }
        }

        public static string GetDesktopFolder()
        {
            string strDesktopFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
            return strDesktopFolderPath;
        }
    }

Categories

Recent posts