Click here to Skip to main content
Click here to Skip to main content
Add your own
alternative version

APJSON

, 28 Aug 2013
This is an alternative for "fastJSON"
Apolyton_FastJson_Binaries__v0.92_.zip
Output
Debug
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
Release x64
Apolyton.FastJson.dll
Release x86
Apolyton.FastJson.dll
consoletest.exe
consoletest.vshost.exe
consoletest.vshost.exe.manifest
fastJSON.dll
Release
Apolyton.FastJson.dll
Silverlight
Apolyton.Json.Silverlight.dll
Apolyton.Json.Silverlight.pdb
Apolyton_FastJson_Binaries__v0.93_.zip
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
consoletest.exe
consoletest.pdb
fastJSON.dll
Apolyton.FastJson.dll
consoletest.exe
consoletest.vshost.exe
fastJSON.dll
Apolyton.FastJson.dll
consoletest.exe
consoletest.vshost.exe
fastJSON.dll
Apolyton.FastJson.dll
consoletest.exe
fastJSON.dll
Apolyton.Json.Silverlight.dll
Apolyton.Json.Silverlight.pdb
Apolyton_FastJson_Binaries__v0.9_.zip
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
consoletest.exe
consoletest.vshost.exe
consoletest.vshost.exe.manifest
fastJSON.dll
fastJSON.pdb
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
consoletest.exe
consoletest.vshost.exe
consoletest.vshost.exe.manifest
fastJSON.dll
fastJSON.pdb
Apolyton.FastJson.dll
consoletest.exe
consoletest.vshost.exe
fastJSON.dll
Apolyton_FastJson_Binaries__v1.0_.zip
Apolyton.FastJson.dll
consoletest.exe
consoletest.vshost.exe
consoletest.vshost.exe.manifest
fastJSON.dll
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
consoletest.exe
consoletest.vshost.exe
fastJSON.dll
fastJSON.pdb
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
consoletest.exe
consoletest.vshost.exe
fastJSON.dll
fastJSON.pdb
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
consoletest.exe
fastJSON.dll
fastJSON.pdb
Apolyton.Json.Silverlight.dll
Apolyton.Json.Silverlight.pdb
Apolyton_FastJson_Sources__v0.92_.zip
Apolyton.FastJson
Apolyton.FastJson.csproj.user
Apolyton.FastJson.Silverlight.csproj.user
Apolyton.FastJson.v11.suo
Bin
Debug
Apolyton.Json.Silverlight.dll
Apolyton.Json.Silverlight.pdb
Common
Data
Diagram.cd
obj
Debug
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
Apolyton.Json.Silverlight.dll
Apolyton.Json.Silverlight.pdb
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
Release x64
Apolyton.FastJson.dll
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
Release x86
Apolyton.FastJson.dll
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
Release
Apolyton.FastJson.dll
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
Properties
Registry
Serialization
Apolyton.FastJson.Tests
bin
Debug
Release
Apolyton.FastJson.dll
Apolyton.FastJSON.Tests.dll
Apolyton.FastJSON.Tests.pdb
Data
Helpers
ComplexTypes
ParameterRelated
Polymorphism
RegistryHelpers
StandardTypes
obj
Debug
Apolyton.FastJson.Tests.csprojResolveAssemblyReference.cache
Apolyton.FastJSON.Tests.dll
Apolyton.FastJSON.Tests.pdb
build.force
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
Release (x86, CUSTOM TYPES)
build.force
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
Release
Apolyton.FastJson.Tests.csprojResolveAssemblyReference.cache
Apolyton.FastJSON.Tests.dll
Apolyton.FastJSON.Tests.pdb
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
Properties
Registry
Serialization
Console Test
bin
Debug
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
consoletest.exe
consoletest.pdb
consoletest.vshost.exe
fastJSON.dll
fastJSON.pdb
x86
DataObjects
obj
Debug
build.force
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
consoletest.pdb
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
Release (x86, CUSTOM TYPES)
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
Release x64
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
Release x86
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
Release
build.force
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
TempPE
x86
Debug
TempPE
Apolyton_FastJson_Sources__v0.93_.zip
Apolyton.FastJson.dll
Apolyton.FastJSON.Tests.dll
Apolyton.FastJSON.Tests.pdb
Apolyton.FastJson.dll
Apolyton.FastJSON.Tests.dll
Apolyton.FastJSON.Tests.pdb
Apolyton.FastJson.Tests.csprojResolveAssemblyReference.cache
Apolyton.FastJSON.Tests.dll
Apolyton.FastJSON.Tests.pdb
DesignTimeResolveAssemblyReferencesInput.cache
build.force
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton.FastJson.Tests.csprojResolveAssemblyReference.cache
Apolyton.FastJSON.Tests.dll
Apolyton.FastJSON.Tests.pdb
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
consoletest.exe
consoletest.pdb
consoletest.vshost.exe
fastJSON.dll
Release
Apolyton.FastJson.dll
consoletest.exe
fastJSON.dll
Release (x86, CUSTOM TYPES)
Apolyton.FastJson.dll
consoletest.exe
fastJSON.dll
Release x64
Apolyton.FastJson.dll
consoletest.exe
fastJSON.dll
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
consoletest.pdb
DesignTimeResolveAssemblyReferencesInput.cache
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
consoletest.pdb
DesignTimeResolveAssemblyReferencesInput.cache
Release x64
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
Release x86
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
Release
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton.FastJson.csproj.user
Apolyton.FastJson.Silverlight.csproj.user
Apolyton.FastJson.v11.suo
Apolyton.Json.Silverlight.dll
Apolyton.Json.Silverlight.pdb
Release
Apolyton.Json.Silverlight.dll
Apolyton.Json.Silverlight.pdb
Diagrams
Json.cd
JsonParameters.cd
TypeDescriptors.cd
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
Apolyton.Json.Silverlight.dll
Apolyton.Json.Silverlight.pdb
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton.FastJson.dll
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton.FastJson.dll
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton.FastJson.dll
Apolyton.Json.Silverlight.dll
Apolyton.Json.Silverlight.pdb
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton_FastJson_Sources__v0.9_.zip
Apolyton.FastJson.csproj.user
Diagram.cd
Apolyton.FastJson.Tests.csprojResolveAssemblyReference.cache
Apolyton.FastJSON.Tests.dll
Apolyton.FastJSON.Tests.pdb
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton.FastJson.Tests.csprojResolveAssemblyReference.cache
Apolyton.FastJSON.Tests.dll
Apolyton.FastJSON.Tests.pdb
DesignTimeResolveAssemblyReferencesInput.cache
build.force
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.vshost.exe
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
consoletest.pdb
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton_FastJson_Sources__v1.0_.zip
Apolyton.FastJson.csproj.user
Apolyton.FastJson.Silverlight.csproj.user
Apolyton.FastJson.v11.suo
Apolyton.Json.Silverlight.dll
Apolyton.Json.Silverlight.pdb
Apolyton.Json.Silverlight.dll
Apolyton.Json.Silverlight.pdb
Json.cd
JsonParameters.cd
TypeDescriptors.cd
Apolyton.FastJson.csprojResolveAssemblyReference.cache
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
Apolyton.Json.Silverlight.dll
Apolyton.Json.Silverlight.pdb
DesignTimeResolveAssemblyReferences.cache
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton.FastJson.dll
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton.FastJson.dll
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton.FastJson.dll
Apolyton.Json.Silverlight.dll
Apolyton.Json.Silverlight.pdb
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
Apolyton.FastJSON.Tests.dll
Apolyton.FastJSON.Tests.pdb
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
Apolyton.FastJSON.Tests.dll
Apolyton.FastJSON.Tests.pdb
Apolyton.FastJson.Tests.csprojResolveAssemblyReference.cache
Apolyton.FastJSON.Tests.dll
Apolyton.FastJSON.Tests.pdb
DesignTimeResolveAssemblyReferencesInput.cache
build.force
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton.FastJson.Tests.csprojResolveAssemblyReference.cache
Apolyton.FastJSON.Tests.dll
Apolyton.FastJSON.Tests.pdb
DesignTimeResolveAssemblyReferencesInput.cache
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
consoletest.exe
consoletest.pdb
consoletest.vshost.exe
fastJSON.dll
fastJSON.pdb
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
consoletest.exe
fastJSON.dll
fastJSON.pdb
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
consoletest.exe
fastJSON.dll
fastJSON.pdb
Apolyton.FastJson.dll
Apolyton.FastJson.pdb
consoletest.exe
fastJSON.dll
fastJSON.pdb
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
consoletest.pdb
DesignTimeResolveAssemblyReferencesInput.cache
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
consoletest.pdb
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
consoletest.csprojResolveAssemblyReference.cache
consoletest.exe
DesignTimeResolveAssemblyReferencesInput.cache
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.Globalization;
using System.IO;
using System.Linq;
using System.Runtime.Serialization;
using System.Text;
using Apolyton.FastJson.Registry;

namespace Apolyton.FastJson
{
    /// <summary>
    /// Represents a json serializer.
    /// </summary>
    /// <remarks>
    /// http://www.codeproject.com/Articles/159450/fastJSON
    /// The version over there (2.0.9) could not be taken directly, as its serializer is taking all public properties, disregarding any attribute policy. This is
    /// not good for our case, as we want to return (portions of) data objects as well.
    /// </remarks>
    internal class JsonSerializer
    {
        private readonly Dictionary<string, int> _globalTypes;

        /// <summary>
        /// The purpose of this dictionar is to reduce the runtime of the long if-else statement in the WriteValue method.
        /// </summary>
        private static readonly Dictionary<Type, Action<JsonSerializer, Object>> _serializerCache;

        protected readonly JsonRegistry _registry;

        private StringBuilder _output = new StringBuilder();
        private StringBuilder _before = new StringBuilder();

        private readonly int _MAX_DEPTH = 10;
        private int _current_depth = 0;
        private bool _typesWritten = false;

        private bool useFastGuid;
        private bool useUtcDateTime;
        private bool useExtensions;
        private bool useGlobalTypes;
        private bool useOptimizedDatasetSchema;
        private bool serializeNullValues;

        static JsonSerializer()
        {
            _serializerCache = new Dictionary<Type, Action<JsonSerializer, Object>>();
        }

        /// <summary>
        /// Creates an instance of the json serializer.
        /// </summary>
        /// <param name="param"></param>
        internal JsonSerializer(JsonParameters param)
        {
            _registry = param.Registry;
            _globalTypes = new Dictionary<string, int>();

            useFastGuid = param.UseFastGuid;
            useUtcDateTime = param.UseUtcDateTime;
            useExtensions = param.UseExtensions;
            useGlobalTypes = param.UsingGlobalTypes;
            useOptimizedDatasetSchema = param.UseOptimizedDatasetSchema;
            serializeNullValues = param.SerializeNullValues;
        }

        /// <summary>
        /// Returns the json string representing the given object.
        /// </summary>
        /// <param name="obj"></param>
        /// <returns></returns>
        internal string Serialize(object obj)
        {
            WriteValue(obj);

            string str = "";

            if (useGlobalTypes && _globalTypes.Count > 0)
            {
                StringBuilder sb = _before;
                sb.Append("\"$types\":{");

                bool pendingSeparator = false;

                foreach (var kv in _globalTypes)
                {
                    if (pendingSeparator) sb.Append(',');
                    pendingSeparator = true;

                    sb.Append("\"").Append(kv.Key).Append("\":\"").Append(kv.Value).Append("\"");
                }

                sb.Append("},")
                  .Append(_output.ToString());

                str = sb.ToString();
            }
            else
            {
                str = _output.ToString();
            }

            return str;
        }

        private void WriteValue(object obj)
        {
            Action<JsonSerializer, object> cachedSerializer;

            if (obj == null || obj is DBNull)
            {
                _output.Append("null");
            }

            else if (obj is string || obj is char)
            {
                WriteString(obj.ToString());
            }
            else if (obj is Guid)
            {
                WriteGuid((Guid)obj);
            }
            else if (obj is bool)
            {
                _output.Append(((bool)obj) ? "true" : "false"); // conform to standard
            }
            else if (
                obj is int || obj is long || obj is double ||
                obj is decimal || obj is float ||
                obj is byte || obj is short ||
                obj is sbyte || obj is ushort ||
                obj is uint || obj is ulong
            )
            {
                _output.Append(((IConvertible)obj).ToString(NumberFormatInfo.InvariantInfo));
            }
            else if (obj is DateTime)
            {
                WriteDateTime((DateTime)obj);
            }
            else if (obj is TimeSpan)
            {
                WriteTimeSpan((TimeSpan)obj);
            }
            else if (_serializerCache.TryGetValue(obj.GetType(), out cachedSerializer))
            {
                cachedSerializer(this, obj);
            }
            else if (obj is IDictionary)
            {
                if (obj.GetType().IsGenericType && obj.GetType().GetGenericArguments()[0] == typeof(string))
                {
                    _serializerCache.Add(obj.GetType(), (ser, arg) => ser.WriteStringDictionary((IDictionary)arg));
                    WriteStringDictionary((IDictionary)obj);
                }
                else
                {
                    _serializerCache.Add(obj.GetType(), (ser, arg) => ser.WriteDictionary((IDictionary)arg));
                    WriteDictionary((IDictionary)obj);
                }
            }
            else if (obj is DataSet)
            {
                _serializerCache.Add(obj.GetType(), (ser, arg) => ser.WriteDataset((DataSet)arg));
                WriteDataset((DataSet)obj);
            }
            else if (obj is DataTable)
            {
                _serializerCache.Add(obj.GetType(), (ser, arg) => ser.WriteDataTable((DataTable)arg));
                WriteDataTable((DataTable)obj);
            }
            else if (obj is byte[])
            {
                _serializerCache.Add(obj.GetType(), (ser, arg) => ser.WriteBytes((byte[])arg));
                WriteBytes((byte[])obj);
            }
            else if (obj is IEnumerable)
            {
                // Just this fix for the byte enumeration makes 10 % performance drop.
                if (obj.GetType().IsGenericType && obj.GetType().GetGenericArguments()[0] == typeof(byte))
                {
                    _serializerCache.Add(obj.GetType(), (ser, arg) => ser.WriteBytes((byte[])arg));
                    WriteBytes((byte[])obj);
                }
                else
                {
                    _serializerCache.Add(obj.GetType(), (ser, arg) => ser.WriteArray((IEnumerable)arg));
                    WriteArray((IEnumerable)obj);
                }
            }
            else if (obj is Enum)
            {
                _serializerCache.Add(obj.GetType(), (ser, arg) => ser.WriteEnum((Enum)arg));
                WriteEnum((Enum)obj);
            }
            else if (_registry.IsCustomTypeRegistered(obj.GetType()))
            {
                WriteCustomType(obj);
            }
            else
            {
                WriteObject(obj);
            }
        }

        private void WriteCustomType(object obj)
        {
            SerializationHandler s;
            _registry._customSerializer.TryGetValue(obj.GetType(), out s);
            WriteStringFast(s(obj));
        }

        private void WriteEnum(Enum e)
        {
            // TODO : optimize enum write
            WriteStringFast(e.ToString());
        }

        private void WriteGuid(Guid g)
        {
            if (useFastGuid == false)
            {
                WriteStringFast(g.ToString());
            }
            else
            {
                WriteBytes(g.ToByteArray());
            }
        }

        private void WriteBytes(byte[] bytes)
        {
            WriteStringFast(Convert.ToBase64String(bytes, 0, bytes.Length, Base64FormattingOptions.None));
        }

        private void WriteTimeSpan(TimeSpan timeSpan)
        {
            _output.Append("\"")
                    .Append(timeSpan.Hours.ToString("00", NumberFormatInfo.InvariantInfo))
                    .Append(":")
                    .Append(timeSpan.Minutes.ToString("00", NumberFormatInfo.InvariantInfo))
                    .Append(":")
                    .Append(timeSpan.Seconds.ToString("00", NumberFormatInfo.InvariantInfo))
                    .Append("\"");
        }

        private void WriteDateTime(DateTime dateTime)
        {
            // datetime format standard : yyyy-MM-dd HH:mm:ss
            DateTime dt = dateTime;

            if (useUtcDateTime && dt.Kind != DateTimeKind.Utc)
            {
                dt = dateTime.ToUniversalTime();
            }

            _output.Append("\"")
                    .Append(dt.Year.ToString("0000", NumberFormatInfo.InvariantInfo))
                    .Append("-")
                    .Append(dt.Month.ToString("00", NumberFormatInfo.InvariantInfo))
                    .Append("-")
                    .Append(dt.Day.ToString("00", NumberFormatInfo.InvariantInfo))
                    .Append(" ")
                    .Append(dt.Hour.ToString("00", NumberFormatInfo.InvariantInfo))
                    .Append(":")
                    .Append(dt.Minute.ToString("00", NumberFormatInfo.InvariantInfo))
                    .Append(":")
                    .Append(dt.Second.ToString("00", NumberFormatInfo.InvariantInfo));

            if (useUtcDateTime)
            {
                _output.Append("Z");
            }

            _output.Append("\"");
        }

        private DatasetSchema GetSchema(DataTable ds)
        {
            if (ds == null) { return null; }

            DatasetSchema m = new DatasetSchema();
            m.Info = new List<string>();
            m.Name = ds.TableName;

            foreach (DataColumn c in ds.Columns)
            {
                m.Info.Add(ds.TableName);
                m.Info.Add(c.ColumnName);
                m.Info.Add(c.DataType.ToString());
            }
            // FEATURE : serialize relations and constraints here

            return m;
        }

        private DatasetSchema GetSchema(DataSet ds)
        {
            if (ds == null) { return null; }

            DatasetSchema m = new DatasetSchema();
            m.Info = new List<string>();
            m.Name = ds.DataSetName;

            foreach (DataTable t in ds.Tables)
            {
                foreach (DataColumn c in t.Columns)
                {
                    m.Info.Add(t.TableName);
                    m.Info.Add(c.ColumnName);
                    m.Info.Add(c.DataType.ToString());
                }
            }
            // FEATURE : serialize relations and constraints here

            return m;
        }

        private string GetXmlSchema(DataTable dt)
        {
            using (var writer = new StringWriter())
            {
                dt.WriteXmlSchema(writer);

                return dt.ToString();
            }
        }

        private void WriteDataset(DataSet ds)
        {
            _output.Append('{');

            if (useExtensions)
            {
                WritePair("$schema", useOptimizedDatasetSchema ? (object)GetSchema(ds) : ds.GetXmlSchema());
                _output.Append(',');
            }

            bool tablesep = false;
            foreach (DataTable table in ds.Tables)
            {
                if (tablesep) _output.Append(",");
                tablesep = true;
                WriteDataTableData(table);
            }

            // end dataset
            _output.Append('}');
        }

        private void WriteDataTableData(DataTable table)
        {
            _output.Append('\"')
                    .Append(table.TableName)
                    .Append("\":[");

            DataColumnCollection cols = table.Columns;
            bool rowseparator = false;

            foreach (DataRow row in table.Rows)
            {
                if (rowseparator) _output.Append(",");
                rowseparator = true;
                _output.Append('[');

                bool pendingSeperator = false;
                foreach (DataColumn column in cols)
                {
                    if (pendingSeperator) _output.Append(',');
                    WriteValue(row[column]);
                    pendingSeperator = true;
                }
                _output.Append(']');
            }


            _output.Append(']');
        }

        private void WriteDataTable(DataTable dt)
        {
            this._output.Append('{');

            if (useExtensions)
            {
                this.WritePair("$schema", useOptimizedDatasetSchema ? (object)this.GetSchema(dt) : this.GetXmlSchema(dt));
                this._output.Append(',');
            }

            WriteDataTableData(dt);

            // end datatable
            this._output.Append('}');
        }

        private void WriteObject(object source)
        {
            if (useGlobalTypes == false)
            {
                _output.Append('{');
            }
            else
            {
                if (_typesWritten == false)
                {
                    _output.Append("{");
                    _before = _output;
                    _output = new StringBuilder();
                }
                else
                {
                    _output.Append("{");
                }
            }

            _typesWritten = true;
            _current_depth++;

            if (_current_depth > _MAX_DEPTH)
            {
                throw new SerializationException("Serializer encountered maximum depth of " + _MAX_DEPTH);
            }

            Type sourceType = source.GetType();
            bool append = false;

            if (useExtensions)
            {
                if (useGlobalTypes == false)
                {
                    WritePairFast("$type", _registry.GetTypeAssemblyName(sourceType));
                }
                else
                {
                    int typeIndex = 0;
                    string typeString = _registry.GetTypeAssemblyName(sourceType);

                    if (_globalTypes.TryGetValue(typeString, out typeIndex) == false)
                    {
                        typeIndex = _globalTypes.Count + 1;
                        _globalTypes.Add(typeString, typeIndex);
                    }

                    WritePairFast("$type", typeIndex.ToString());
                }
                append = true;
            }

            IEnumerable<GetterDescriptor> getters = _registry.GetGetters(sourceType);
            int count = getters.Count();
            int i = count;

            if (useExtensions) // count $type as a property
            {
                i++;
            }

            Dictionary<string, string> map = null;

            foreach (var descriptor in getters)
            {
                i--;

                if (append && i > 0)
                {
                    _output.Append(',');
                }

                object value = descriptor.Getter(source);
                if (serializeNullValues == false && (value == null || value is DBNull))
                {
                    append = false;
                }
                else
                {
                    if (i == 0 && count > 1) // last non null
                    {
                        _output.Append(",");
                    }

                    WritePair(descriptor.Name, value);

                    if (value != null && useExtensions)
                    {
                        Type valueType = descriptor.PropertyOrFieldType;

                        if (valueType == typeof(Object))
                        {
                            if (map == null) { map = new Dictionary<string, string>(); }

                            map.Add(descriptor.Name, valueType.ToString());
                        }
                    }

                    append = true;
                }
            }

            if (map != null && map.Count > 0)
            {
                _output.Append(",\"$map\":");
                WriteStringDictionary(map);
            }

            _current_depth--;
            _output.Append('}');
            _current_depth--;
        }

        private void WritePairFast(string name, string value)
        {
            if ((value == null) && serializeNullValues == false)
            {
                return;
            }

            WriteStringFast(name);

            _output.Append(':');

            WriteStringFast(value);
        }

        private void WritePair(string name, object value)
        {
            if ((value == null || value is DBNull) && serializeNullValues == false)
            {
                return;
            }

            WriteStringFast(name);

            _output.Append(':');

            WriteValue(value);
        }

        private void WriteArray(IEnumerable array)
        {
            _output.Append('[');

            bool pendingSeperator = false;

            foreach (object obj in array)
            {
                if (pendingSeperator) _output.Append(',');

                WriteValue(obj);

                pendingSeperator = true;
            }

            _output.Append(']');
        }

        private void WriteStringDictionary(IDictionary dic)
        {
            _output.Append('{');

            bool pendingSeparator = false;

            foreach (DictionaryEntry entry in dic)
            {
                if (pendingSeparator) _output.Append(',');

                WritePair((string)entry.Key, entry.Value);

                pendingSeparator = true;
            }

            _output.Append('}');
        }

        private void WriteDictionary(IDictionary dic)
        {
            _output.Append('[');

            bool pendingSeparator = false;

            foreach (DictionaryEntry entry in dic)
            {
                if (pendingSeparator) { _output.Append(','); }

                _output.Append('{');
                WritePair("k", entry.Key);

                _output.Append(",");
                WritePair("v", entry.Value);

                _output.Append('}');
                pendingSeparator = true;
            }

            _output.Append(']');
        }

        /// <summary>
        /// Writes a string without masking it.
        /// </summary>
        /// <param name="s"></param>
        private void WriteStringFast(string s)
        {
            _output.Append('\"');
            _output.Append(s);
            _output.Append('\"');
        }

        /// <summary>
        /// Writes a masked string (may contain multiple lines etc);
        /// </summary>
        /// <param name="s"></param>
        private void WriteString(string s)
        {
            _output.Append('\"');

            int runIndex = -1;

            for (var index = 0; index < s.Length; ++index)
            {
                var c = s[index];

                if (c >= ' ' && c < 128 && c != '\"' && c != '\\')
                {
                    if (runIndex == -1)
                    {
                        runIndex = index;
                    }

                    continue;
                }

                if (runIndex != -1)
                {
                    _output.Append(s, runIndex, index - runIndex);
                    runIndex = -1;
                }

                switch (c)
                {
                    case '\t': _output.Append("\\t"); break;
                    case '\r': _output.Append("\\r"); break;
                    case '\n': _output.Append("\\n"); break;
                    case '"':
                    case '\\': _output.Append('\\'); _output.Append(c); break;
                    default:
                        _output.Append("\\u");
                        _output.Append(((int)c).ToString("X4", NumberFormatInfo.InvariantInfo));
                        break;
                }
            }

            if (runIndex != -1)
            {
                _output.Append(s, runIndex, s.Length - runIndex);
            }

            _output.Append('\"');
        }
    }
}

By viewing downloads associated with this article you agree to the Terms of Service and the article's licence.

If a file you wish to view isn't highlighted, and is a text file (not binary), please let us know and we'll add colourisation support for it.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

Aron Kovacs

Germany Germany
No Biography provided

| Advertise | Privacy | Mobile
Web03 | 2.8.140721.1 | Last Updated 28 Aug 2013
Article Copyright 2012 by Aron Kovacs
Everything else Copyright © CodeProject, 1999-2014
Terms of Service
Layout: fixed | fluid