Page tree

Introduction

BSON simply stands for “Binary JSON,” and that’s exactly what it was invented to be. BSON’s binary structure encodes type and length information, which allows it to be parsed much more quickly.

JSON vs BSON


JSONBSON
EncodingUTF-8 StringBinary
Data SupportString, Boolean, Number, ArrayString, Boolean, Number (Integer, Float, Long, Decimal128...), Array, Date, Raw Binary
ReadabilityHuman and MachineMachine Only

How to serialize in BSon format

To serialize to BSon format, it is exactly the same option as for JSON with the difference that the DefaultSerializer must be to BSonSerializer.

Here is the code which will be generated in your classes or in a base class according to your options :

public partial class EntityBase<T> : INotifyPropertyChanged
    
    {
        private static JsonSerializer _serializer;
        private static JsonSerializer SerializerBson
        {
            get
            {
                if ((_serializer == null))
                {
                    _serializer = new JsonSerializer();
                }
                return _serializer;
            }
        }
        
        public event System.ComponentModel.PropertyChangedEventHandler PropertyChanged;
        
        public virtual void OnPropertyChanged(string propertyName)
        {
            System.ComponentModel.PropertyChangedEventHandler handler = PropertyChanged;
            if ((handler != null))
            {
                handler(this, new System.ComponentModel.PropertyChangedEventArgs(propertyName));
            }
        }
        
        #region Serialize/Deserialize
        /// <summary>
        /// Serializes current EntityBase object into an XML string
        /// </summary>
        /// <returns>string XML value</returns>
        public virtual string Serialize()
        {
            MemoryStream memoryStream = null;
            try
            {
                memoryStream = new MemoryStream();
                BsonDataWriter bsonDataWriter = new BsonDataWriter(memoryStream);
                SerializerBson.Serialize(bsonDataWriter, this);
                return Convert.ToBase64String(memoryStream.ToArray());
            }
            finally
            {
                if ((memoryStream != null))
                {
                    memoryStream.Dispose();
                }
            }
        }
        
        /// <summary>
        /// Deserializes EntityBase object
        /// </summary>
        /// <param name="input">string workflow markup to deserialize</param>
        /// <param name="obj">Output EntityBase object</param>
        /// <param name="exception">output Exception value if deserialize failed</param>
        /// <returns>true if this Serializer can deserialize the object; otherwise, false</returns>
        public static bool Deserialize(string input, out T obj, out Exception exception)
        {
            exception = null;
            obj = default(T);
            try
            {
                obj = Deserialize(input);
                return true;
            }
            catch (Exception ex)
            {
                exception = ex;
                return false;
            }
        }
        
        public static bool Deserialize(string input, out T obj)
        {
            Exception exception = null;
            return Deserialize(input, out obj, out exception);
        }
        
        /// <returns>string XML value</returns>
        public new static T Deserialize(string input)
        {
            MemoryStream memoryStream = null;
            try
            {
                byte[] data;
                data = Convert.FromBase64String(input);
                memoryStream = new MemoryStream(data);
                BsonDataReader bsonDataReader = new BsonDataReader(memoryStream);
                return SerializerBson.Deserialize<T>(bsonDataReader);
            }
            finally
            {
                if ((memoryStream != null))
                {
                    memoryStream.Dispose();
                }
            }
        }
        #endregion
        
        public virtual void SaveToFile(string fileName)
        {
            StreamWriter streamWriter = null;
            try
            {
                string dataString = Serialize();
                FileInfo outputFile = new FileInfo(fileName);
                streamWriter = outputFile.CreateText();
                streamWriter.WriteLine(dataString);
                streamWriter.Close();
            }
            finally
            {
                if ((streamWriter != null))
                {
                    streamWriter.Dispose();
                }
            }
        }
        
        public new static T LoadFromFile(string fileName)
        {
            FileStream file = null;
            StreamReader sr = null;
            try
            {
                file = new FileStream(fileName, FileMode.Open, FileAccess.Read);
                sr = new StreamReader(file);
                string dataString = sr.ReadToEnd();
                sr.Close();
                file.Close();
                return Deserialize(dataString);
            }
            finally
            {
                if ((file != null))
                {
                    file.Dispose();
                }
                if ((sr != null))
                {
                    sr.Dispose();
                }
            }
        }
        #endregion
    }
    #endregion
    


The Serialize() method returns a string to Base64. The deserialize() method takes as parameter a base64 string.




  • No labels