Ejemplo n.º 1
0
        public virtual string NKserialize(object obj)
        {
            IFormatProvider invariant = System.Globalization.CultureInfo.InvariantCulture;
            Type            t         = obj.GetType();
            TypeInfo        ti        = t.GetTypeInfo();

            if (obj == null)
            {
                return("undefined");
            }

            if (obj != null && obj.GetType().GetTypeInfo().IsPrimitive)
            {
                // The primitive types are Boolean, Byte, SByte, Int16, UInt16, Int32, UInt32, Int64, UInt64, IntPtr, UIntPtr, Char, Double, and Single.
                if (obj is Char)
                {
                    return("'" + Convert.ToString(((Char)obj), invariant) + "'");
                }

                if (obj is Boolean)
                {
                    return((Boolean)obj ? "true" : "false");
                }

                return(Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture));
            }

            if (obj is NKScriptValue)
            {
                return(((NKScriptValue)obj).ns);
            }

            if (obj is NKScriptExport)
            {
                var scriptValueObject = obj.getNKScriptValue();
                if (scriptValueObject != null)
                {
                    return(scriptValueObject.ns);
                }
                var newScriptValueObject = new NKScriptValueNative(obj, (NKScriptContext)this);
                return(newScriptValueObject.ns);
            }

            if (obj is string)
            {
                var str = NKData.jsonSerialize((string)obj);
                return(str); //  str.Substring(1, str.Length - 2);
            }

            if (obj is DateTime)
            {
                return("\"" + ((DateTime)obj).ToString("u") + "\"");
            }

            if (typeof(IDictionary).GetTypeInfo().IsAssignableFrom(ti))
            {
                var genericKey = ti.GenericTypeArguments[0];
                if (typeof(string).GetTypeInfo().IsAssignableFrom(genericKey.GetTypeInfo()))
                {
                    var dict = (IDictionary <string, dynamic>)obj;
                    return("{" + string.Join(", ", dict.Keys.Select(k => "\"" + k + "\":" + NKserialize(dict[k]))) + "}");
                }
            }

            if (typeof(IEnumerable).GetTypeInfo().IsAssignableFrom(ti))
            {
                return("[" + string.Join(", ", ((IEnumerable <dynamic>)obj).Select(o => NKserialize(o))) + "]");
            }

            return(Convert.ToString(obj, System.Globalization.CultureInfo.InvariantCulture));
        }
Ejemplo n.º 2
0
        public virtual object NKdeserialize(string json)
        {
            var obj = NKData.jsonDeserialize(json);

            return(obj);
        }