Posts tagged ‘serialize’

Json in C# – Part 2

I posted before Json in C# but I was not satisfied with what I found so far. I went looking again and found some C# classes in the newer frameworks. namely JavaScriptSerializer. Let’s take a look with a simple json data feed.

using System.Web.Script.Serialization;
   
    internal static class Program
    {
        class CarList
        {
            public List<Car> cars;
        }
        class Car
        {
            public string model = string.Empty;
            public int year = 0;
        }

        private static void Main(string[] args)
        {
            string jsonString = “{\”cars\”:[{\”model\”:\”Ford 350\”,\”year\”:2007},{\”model\”:\”Buick Skylark\”,\”year\”:1953},{\”model\”:\”Honda Civic\”,\”year\”:2002}]}”;

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            CarList carObjects = serializer.Deserialize<CarList>(jsonString);
            Console.WriteLine(“cars count=” + carObjects.cars.Count);
        }



As far as I can tell JavaScriptSerializer was introduced in .Net 3.0, but depreciated in 3.5. Instead your supposed to use DataContractJsonSerializer. With that change you need to add serialize attribute to your classes, you also need to include Xml and serialization libs. Let’s take a look at the new code.

using System.Runtime.Serialization.Json;

    internal static class Program
    {
        [Serializable]
        class CarList
        {
            public List<Car> cars;
        }
        [Serializable]
        class Car
        {
            public string model = string.Empty;
            public int year = 0;
        }

        private static void Main(string[] args)
        {
            string jsonString = “{\”cars\”:[{\”model\”:\”Ford 350\”,\”year\”:2007},{\”model\”:\”Buick Skylark\”,\”year\”:1953},{\”model\”:\”Honda Civic\”,\”year\”:2002}]}”;
            //         
            DataContractJsonSerializer jsonserialize = new DataContractJsonSerializer(typeof(CarList));
            Stream jsonStream = new MemoryStream(ASCIIEncoding.Default.GetBytes(jsonString));
            CarList carObjectsj = (CarList)jsonserialize.ReadObject(jsonStream);
            Console.WriteLine(“cars count=” + carObjectsj.cars.Count);
        }



As a curve ball Microsoft decided to Un-depreciate the JavaScriptSerializer in .Net 3.5 SP1, which is good news. It’s easier coding when using the JavaScriptSerializer. I don’t know if both classes will be permanently available, we will see.

C# Xml database

I was thinking I needed a small footprint database the other day when coding a small app. If you need something to save small amount of data you can just serialize it to Xml file and back. There is your little database. Obviously not very usable for heavy load, but with a small amount of data it works just fine. There is not much involved lets take a look.

public class Car
    {
        public string Model = string.Empty;
        public int Year = 0;
        //
        public Car() {}
    }

        /// Reads car objects from xml file
        public static List<Car> readXML()
        {
            // Trap
            if (!File.Exists(XML_FILE)) return new List<Car>();

            // Deserialize, load from XML
            FileStream fs = new FileStream(XML_FILE, FileMode.Open);
            XmlReader reader = new XmlTextReader(fs);
            XmlSerializer ser = new XmlSerializer(typeof(List<Car>));
            List<Car> myList = (List<Car>)ser.Deserialize(reader);
            fs.Close();
            //
            return myList;
        }

        /// Writes car objects to xml file
        public static void writeXML(List<Car> plStocks)
        {
            // Now create the Xml
            XmlSerializer s = new XmlSerializer(typeof(List<Car>));
            TextWriter writer = new StreamWriter(XML_FILE);
            // Serializes the objects in list
            s.Serialize(writer, plStocks);
            // done, close the file
            writer.Close();
        }