Click here to Skip to main content
15,894,630 members
Articles / Programming Languages / Markdown

APJSON

Rate me:
Please Sign up or sign in to vote.
4.67/5 (5 votes)
28 Aug 2013CPOL13 min read 41.8K   1.2K   34  
This is an alternative for "fastJSON"
using System;
using System.Diagnostics;
using System.Linq;
using Apolyton.FastJson.Registry;
using Apolyton.FastJson.Serialization;

namespace Apolyton.FastJson.Data
{
    /// <summary>
    /// Represents a json primitive value.
    /// </summary>
    public struct JsonPrimitive : IJsonValue, IConvertible
    {
        private readonly JsonRegistry _registry;
        private readonly String _localValue;
        private object _typedValue;
        private DeserializationHandler _deserializationHandler;

        #region Constructors

        /// <summary>
        /// Creates an instance of the type.
        /// </summary>
        /// <param name="localValue">The string representation of the Json Primitive.</param>
        public JsonPrimitive(String localValue)
        {
            this._deserializationHandler = null;
            this._registry = null;
            this._localValue = localValue;
            this._typedValue = null;
        }

        /// <summary>
        /// Creates an instance of the type.
        /// </summary>
        /// <param name="boolean"></param>
        internal JsonPrimitive(bool boolean)
        {
            this._deserializationHandler = null;
            this._registry = null;
            this._localValue = null;
            this._typedValue = boolean;
        }

        /// <summary>
        /// Creates an instance of the primitive.
        /// </summary>
        /// <param name="localValue">The string representation of the Json Primitive.</param>
        /// <param name="parameters">The registry of the given parameters will be used to resolve the custom deserializer, if required.</param>
        public JsonPrimitive(JsonParameters parameters, String localValue)
            : this (parameters.Registry, localValue)
        {
        }

        /// <summary>
        /// Creates an instance of the primitive.
        /// </summary>
        /// <param name="localValue">The string representation of the Json Primitive.</param>
        /// <param name="registry">The registry which is used to resolve the custom deserializer, if required.</param>
        internal JsonPrimitive(JsonRegistry registry, String localValue)
        {
            this._deserializationHandler = null;
            this._registry = registry;
            this._localValue = localValue;
            this._typedValue = null;
        }

        #endregion

        /// <summary>
        /// Gets the json primitive type.
        /// </summary>
        public JsonType Type
        {
            get { return JsonType.JsonPrimitive; }
        }

        /// <summary>
        /// Returns json primitive.
        /// </summary>
        /// <returns></returns>
        public override string ToString()
        {
            return "JsonPrimitive";
        }

        /// <summary>
        /// Gets the value as string.
        /// </summary>
        [DebuggerDisplay("Click to expand. This operation has side effects.")]
        public string AsString
        {
            get
            {
                if (_typedValue == null)
                {
                    _typedValue = Deserialization.ChangeType(_localValue, typeof(String));
                }

                return (string)_typedValue;
            }
        }

        /// <summary>
        /// Gets the value as integer.
        /// </summary>
        [DebuggerDisplay("Click to expand. This operation has side effects.")]
        public int AsInteger
        {
            get
            {
                if (_typedValue == null)
                {
                    _typedValue = Int32.Parse(_localValue);
                }

                return (int)_typedValue;
            }
        }


        /// <summary>
        /// Gets the value as bool.
        /// </summary>
        [DebuggerDisplay("Click to expand. This operation has side effects.")]
        public bool AsBool
        {
            get
            {
                if (_typedValue == null)
                {
                    _typedValue = bool.Parse(_localValue);
                }

                return (bool)_typedValue;
            }
        }

        /// <summary>
        /// Gets the value as double.
        /// </summary>
        [DebuggerDisplay("Click to expand. This operation has side effects.")]
        public Double AsDouble
        {
            get
            {
                if (_typedValue == null)
                {
                    _typedValue = double.Parse(_localValue);
                }

                return (Double)_typedValue;
            }
        }

        /// <summary>
        /// Gets the value as float.
        /// </summary>
        [DebuggerDisplay("Click to expand. This operation has side effects.")]
        public float AsFloat
        {
            get
            {
                if (_typedValue == null)
                {
                    _typedValue = float.Parse(_localValue);
                }

                return (float)_typedValue;
            }
        }

        /// <summary>
        /// Gets the value as date time.
        /// </summary>
        [DebuggerDisplay("Click to expand. This operation has side effects.")]
        public DateTime AsDateTime
        {
            get
            {
                if (_typedValue == null)
                {
                    // Since JsonPrimitive is a generic value, we cannot specify the date time kind we want. Instead, we take it as it is
                    // Later, when the real object is built (and if), the adjustment is done over there.
                    _typedValue = Deserialization.CreateDateTime(_localValue, DateTimeKind.Unspecified);
                }

                return (DateTime)_typedValue;
            }
        }

        /// <summary>
        /// Gets the value as time span.
        /// </summary>
        [DebuggerDisplay("Click to expand. This operation has side effects.")]
        public TimeSpan AsTimeSpan
        {
            get
            {
                if (_typedValue == null)
                {
                    _typedValue = TimeSpan.Parse(_localValue);
                }

                return (TimeSpan)_typedValue;
            }
        }

        /// <summary>
        /// Gets the value as guid.
        /// </summary>
        [DebuggerDisplay("Click to expand. This operation has side effects.")]
        public Guid AsGuid
        {
            get
            {
                if (_typedValue == null)
                {
                    _typedValue = Deserialization.CreateGuid(_localValue);
                }

                return (Guid)_typedValue;
            }
        }

        /// <summary>
        /// Gets the value as long.
        /// </summary>
        [DebuggerDisplay("Click to expand. This operation has side effects.")]
        public long AsLong
        {
            get
            {
                if (_typedValue == null)
                {
                    _typedValue = Deserialization.CreateLong(_localValue);
                }

                return (long)_typedValue;
            }
        }

        public int Count
        {
            get { throw new NotSupportedException(); }
        }

        public IJsonValue this[int i]
        {
            get { throw new NotSupportedException(); }
        }

        public IJsonValue this[string key]
        {
            get { throw new NotSupportedException(); }
        }

        #region IConvertible Members

        TypeCode IConvertible.GetTypeCode()
        {
            return TypeCode.Boolean | TypeCode.Char | TypeCode.DateTime | TypeCode.Decimal | TypeCode.Double | TypeCode.Int16 | TypeCode.Int32 | TypeCode.Int64
                | TypeCode.String | TypeCode.UInt16 | TypeCode.UInt32 | TypeCode.UInt64;
        }

        bool IConvertible.ToBoolean(IFormatProvider provider)
        {
            return AsBool;
        }

        byte IConvertible.ToByte(IFormatProvider provider)
        {
            throw new NotSupportedException();
        }

        char IConvertible.ToChar(IFormatProvider provider)
        {
            if (_typedValue == null)
            {
                _typedValue = _localValue.ToCharArray().First();
            }

            return (char)_typedValue;
        }

        DateTime IConvertible.ToDateTime(IFormatProvider provider)
        {
            return AsDateTime;
        }

        decimal IConvertible.ToDecimal(IFormatProvider provider)
        {
            return AsInteger;
        }

        double IConvertible.ToDouble(IFormatProvider provider)
        {
            return AsDouble;
        }

        short IConvertible.ToInt16(IFormatProvider provider)
        {
            return (short)AsInteger;
        }

        int IConvertible.ToInt32(IFormatProvider provider)
        {
            return AsInteger;
        }

        long IConvertible.ToInt64(IFormatProvider provider)
        {
            return AsLong;
        }

        sbyte IConvertible.ToSByte(IFormatProvider provider)
        {
            throw new NotImplementedException();
        }

        float IConvertible.ToSingle(IFormatProvider provider)
        {
            return AsFloat;
        }

        string IConvertible.ToString(IFormatProvider provider)
        {
            return _localValue;
        }

        object IConvertible.ToType(Type conversionType, IFormatProvider provider)
        {
            if (conversionType == typeof(Guid))
            {
                return AsGuid;
            }
            else if (conversionType == typeof(TimeSpan))
            {
                return AsTimeSpan;
            }
            else if (conversionType.IsEnum)
            {
                if (_typedValue != null) { return _typedValue; }
                else { _typedValue = Deserialization.CreateEnum(conversionType, _localValue); ; return _typedValue; }
            }
            else if (conversionType == typeof(byte[]))
            {
                if (_typedValue != null) { return _typedValue; }
                else { _typedValue = Deserialization.CreateByteArray(_localValue, typeof(byte[])); return _typedValue; }
            }
            else if (_registry != null && _registry._customDeserializer.TryGetValue(conversionType, out _deserializationHandler))
            {
                if (_typedValue != null) { return _typedValue; }
                else { _typedValue = _deserializationHandler(_localValue); return _typedValue; }
            }
            else if (conversionType == typeof(int?))
            {
                if (_localValue != null) { return AsInteger; }
                else { return null; }
            }
            else if (conversionType == typeof(double?))
            {
                if (_localValue != null) { return AsDouble; }
                else { return null; }
            }
            else if (conversionType == typeof(Guid?))
            {
                if (_localValue != null) { return AsGuid; }
                else { return null; }
            }
            else if (conversionType == typeof(short?))
            {
                if (_localValue != null) { return (short)AsInteger; }
                else { return null; }
            }
            else if (conversionType == typeof(long?))
            {
                if (_localValue != null) { return AsLong; }
                else { return null; }
            }
            else if (conversionType == typeof(DateTime?))
            {
                if (_localValue != null) { return AsDateTime; }
                else { return null; }
            }
            else if (conversionType == typeof(TimeSpan?))
            {
                if (_localValue != null) { return AsTimeSpan; }
                else { return null; }
            }
            else if (conversionType == typeof(float?))
            {
                if (_localValue != null) { return AsFloat; }
                else if (_localValue == null) { return null; }
                else { return null; }
            }
            else if (conversionType == typeof(uint?))
            {
                if (_typedValue != null) { return _typedValue; }
                else if (_localValue == null) { return null; }
                else { _typedValue = uint.Parse(_localValue); return _typedValue; }
            }
            else if (conversionType == typeof(ushort?))
            {
                if (_typedValue != null) { return _typedValue; }
                else if (_localValue == null) { return null; }
                else { _typedValue = ushort.Parse(_localValue); return _typedValue; }
            }
            else if (conversionType == typeof(ulong?))
            {
                if (_typedValue != null) { return _typedValue; }
                else if (_localValue == null) { return null; }
                else { _typedValue = ulong.Parse(_localValue); return _typedValue; }
            }
            else if (conversionType == typeof(decimal))
            {
                if (_typedValue != null) { return _typedValue; }
                else { _typedValue = decimal.Parse(_localValue); return _typedValue; }
            }
            else if (conversionType == typeof(decimal?))
            {
                if (_typedValue != null) { return _typedValue; }
                else if (_localValue == null) { return null; }
                else { _typedValue = decimal.Parse(_localValue); return _typedValue; }
            }
            else
            {
                throw new NotSupportedException("Cannot convert json primitive to: " + conversionType.ToString());
            }
        }

        ushort IConvertible.ToUInt16(IFormatProvider provider)
        {
            if (_typedValue == null)
            {
                _typedValue = ushort.Parse(_localValue);
            }

            return (ushort)_typedValue;
        }

        uint IConvertible.ToUInt32(IFormatProvider provider)
        {
            if (_typedValue == null)
            {
                _typedValue = UInt32.Parse(_localValue);
            }

            return (UInt32)_typedValue;
        }

        ulong IConvertible.ToUInt64(IFormatProvider provider)
        {
            if (_typedValue == null)
            {
                _typedValue = UInt64.Parse(_localValue);
            }

            return (UInt64)_typedValue;
        }

        #endregion
    }
}

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)


Written By
Germany Germany
This member has not yet provided a Biography. Assume it's interesting and varied, and probably something to do with programming.

Comments and Discussions