static NameValueCollection CreateNameValueCollection(JsonDict d)
        {
            var nv = new NameValueCollection();

            foreach (var o in d)
            {
                var k  = o.Key;
                var ov = o.Value;
                if (ov == null)
                {
                    nv.Add(k, null);
                    continue;
                }
                var s = ov as string;
                if (s != null)
                {
                    nv.Add(k, s);
                    continue;
                }
                var sa = ov as IList;
                if (sa != null)
                {
                    foreach (string item in sa)
                    {
                        nv.Add(k, item);
                    }
                    continue;
                }
                nv.Add(k, ov.ToString());
            }

            return(nv);
        }
Exemple #2
0
        JsonDict ParseObject()
        {
            var table = new JsonDict();

            ConsumeToken();              // {

            while (true)
            {
                switch (LookAhead())
                {
                case Token.Comma:
                    ConsumeToken();
                    break;

                case Token.Curly_Close:
                    ConsumeToken();
                    return(table);

                default:
                {
                    // name
                    string name = ParseString();

                    // :
                    if (NextToken() != Token.Colon)
                    {
                        throw new JsonParserException("Expected colon at index ", _index, GetContextText());
                    }

                    // value
                    object value = ParseValue();

                    if (name.Length == 0)
                    {
                        // ignores unnamed item
                        continue;
                    }
                    if (name[0] == '$')
                    {
                        switch (name)
                        {
                        case JsonDict.ExtType: table.Type = (string)value; continue;

                        case JsonDict.ExtRefIndex: table.RefIndex = (int)(long)value; continue;

                        case JsonDict.ExtSchema: table.Schema = value; continue;

                        default:
                            break;
                        }
                    }
                    table.Add(new KeyValuePair <string, object> (name, value));
                }
                break;
                }
            }
        }
        static StringDictionary CreateStringDictionary(JsonDict d)
        {
            var nv = new StringDictionary();

            foreach (var o in d)
            {
                nv.Add(o.Key, (string)o.Value);
            }

            return(nv);
        }
        object CreateStringKeyDictionary(JsonDict reader, SerializationInfo pt)
        {
            var col = (IDictionary)pt.Instantiate();
            // NOTE: argument 0 is not used
            var ec = pt.TypeParameters != null ? pt.TypeParameters[1] : null;
            var m  = ec != null ? ec.DeserializeMethod : RevertUndefined;

            foreach (KeyValuePair <string, object> values in reader)
            {
                col.Add(values.Key, m(this, values.Value, ec));
            }
            return(col);
        }
        DataSet CreateDataSet(JsonDict reader)
        {
            var ds = new DataSet();

            ds.EnforceConstraints = false;
            ds.BeginInit();

            // read dataset schema here
            var schema = reader.Schema;

            if (schema is string)
            {
                TextReader tr = new StringReader((string)schema);
                ds.ReadXmlSchema(tr);
            }
            else
            {
                var ms = (DatasetSchema)CreateObject((JsonDict)schema, _manager.GetSerializationInfo(typeof(DatasetSchema)), null);
                ds.DataSetName = ms.Name;
                for (int i = 0; i < ms.Info.Count; i += 3)
                {
                    if (ds.Tables.Contains(ms.Info[i]) == false)
                    {
                        ds.Tables.Add(ms.Info[i]);
                    }
                    ds.Tables[ms.Info[i]].Columns.Add(ms.Info[i + 1], Type.GetType(ms.Info[i + 2]));
                }
            }

            foreach (KeyValuePair <string, object> pair in reader)
            {
                //if (pair.Key == "$type" || pair.Key == "$schema") continue;

                var rows = (JsonArray)pair.Value;
                if (rows == null)
                {
                    continue;
                }

                ReadDataTable(rows, ds.Tables[pair.Key]);
            }

            ds.EndInit();

            return(ds);
        }
        DataTable CreateDataTable(JsonDict reader)
        {
            var dt = new DataTable();

            // read dataset schema here
            var schema = reader.Schema;

            if (schema is string)
            {
                using (var tr = new StringReader((string)schema)) {
                    dt.ReadXmlSchema(tr);
                }
            }
            else
            {
                var ms = (DatasetSchema)CreateObject((JsonDict)schema, _manager.GetSerializationInfo(typeof(DatasetSchema)), null);
                dt.TableName = ms.Info[0];
                for (int i = 0; i < ms.Info.Count; i += 3)
                {
                    dt.Columns.Add(ms.Info[i + 1], Reflection.GetTypeFromCache(ms.Info[i + 2]));
                }
            }

            foreach (var pair in reader)
            {
                //if (pair.Key == "$type" || pair.Key == "$schema")
                //	continue;

                var rows = (JsonArray)pair.Value;
                if (rows == null)
                {
                    continue;
                }

                if (!dt.TableName.Equals(pair.Key, StringComparison.InvariantCultureIgnoreCase))
                {
                    continue;
                }

                ReadDataTable(rows, dt);
            }

            return(dt);
        }
        /// <summary>
        /// Deserializes an object.
        /// </summary>
        /// <param name="data">The data to be deserialized.</param>
        /// <param name="type">The reflection cache of the type.</param>
        /// <param name="input">The data container. If this value is not null, deserialized members will be written to it. If null, new object will be created.</param>
        /// <returns>The deserialized object.</returns>
        /// <exception cref="JsonSerializationException">Cannot determine type from <paramref name="data"/>.</exception>
        internal object CreateObject(JsonDict data, SerializationInfo type, object input)
        {
            if (data.RefIndex > 0)
            {
                object v = null;
                _cirrev.TryGetValue(data.RefIndex, out v);
                return(v);
            }

            if (String.IsNullOrEmpty(data.Type) == false)
            {
                type = _manager.GetSerializationInfo(data.Type);
                if (type == null)
                {
                    type = _manager.GetSerializationInfo(Reflection.GetTypeFromCache(data.Type));
                }
            }
            if (type != null && typeof(object).Equals(type.Reflection.Type))
            {
                return(data);
            }

            if (type == null)
            {
                throw new JsonSerializationException("Cannot determine type");
            }

            object o = input;

            if (o == null)
            {
                o = _manager.ParametricConstructorOverride
                                        ? System.Runtime.Serialization.FormatterServices.GetUninitializedObject(type.Reflection.Type)
                                        : type.Instantiate();
            }
            int circount = 0;

            // dictionary lookup makes it impossible to use objects with a custom GetHashCode based on (unchanging) properties:
            if (_circobj.TryGetValue(o, out circount) == false)
            {
                circount = _circobj.Count + 1;
                _circobj.Add(o, circount);
                _cirrev.Add(circount, o);
            }

            var si = type.Interceptor;

            if (si != null)
            {
                si.OnDeserializing(o);
            }
            var props = type.Setters;

            foreach (var kv in data)
            {
                var n = kv.Key;
                var v = kv.Value;
                JsonMemberSetter pi;
                // field name is not defined
                if (props.TryGetValue(n, out pi) == false)
                {
                    continue;
                }
                if (pi.CanWrite == false && pi.Member.JsonDataType != JsonDataType.List)
                {
                    continue;
                }
                var  m         = pi.Member;
                var  ji        = new JsonItem(n, v, false);
                bool converted = false;
                // TODO: Convert items for types implements IEnumerable and Add(?) method
                if (v is IList && pi.ItemConverter != null)
                {
                    ji._Value = ConvertItems(pi, v as IList);
                }
                if (pi.Converter != null || pi.TypeInfo.Converter != null)
                {
                    ConvertProperty(o, pi, ji);
                }

                object oset = null;
                // use the converted value
                if (converted || ReferenceEquals(ji._Value, v) == false)
                {
                    if (pi.CanWrite == false && m.JsonDataType == JsonDataType.List)
                    {
                        ji._Value = CreateList((JsonArray)ji._Value, pi.TypeInfo, m.Getter(o));
                    }
                    if (ji._Value != null || m.IsClass || m.IsNullable)
                    {
                        oset = ji._Value;
                        goto SET_VALUE;
                    }
                    continue;
                }
                // process null value
                if (ji._Value == null)
                {
                    var i = new JsonItem(n, null, false);
                    if (si != null && si.OnDeserializing(o, i) == false)
                    {
                        continue;
                    }
                    if (i.Value != null || m.IsClass || m.IsNullable)
                    {
                        o = m.Setter(o, i.Value);
                    }
                    continue;
                }
                v = ji._Value;
                // set member value
                switch (m.JsonDataType)
                {
                case JsonDataType.Undefined: goto default;

                case JsonDataType.Int: oset = v is long?(int)(long)v : v is double?(int)(double)v : v is string?ValueConverter.ToInt32((string)v) : v is bool && (bool)v ? 1 : 0; break;

                case JsonDataType.String: oset = v is string?(string)v: v is double?((double)v).ToString() : v is long?ValueConverter.Int64ToString((long)v) : v is bool?((bool)v).ToString() : null; break;

                case JsonDataType.Bool: oset = v is bool?(bool)v : v is double?(double)v != 0 : v is long?(long)v != 0 : v is string?ValueConverter.ToBoolean((string)v) : false; break;

                case JsonDataType.Long: oset = v is long?(long)v : v is double?(long)(double)v : v is string?ValueConverter.ToInt64((string)v) : v is bool && (bool)v ? 1L : 0L; break;

                case JsonDataType.Double: oset = v is double?(double)v: v is long?(double)(long)v : v is string?ValueConverter.ToDouble((string)v) : v is bool && (bool)v ? 1D : 0D; break;

                case JsonDataType.Single: oset = v is double?(float)(double)v: v is long?(float)(long)v : v is string?ValueConverter.ToSingle((string)v) : v is bool && (bool)v ? 1F : 0F; break;

                case JsonDataType.DateTime: oset = CreateDateTime(this, v); break;

                case JsonDataType.Guid: oset = CreateGuid(v); break;

                case JsonDataType.ByteArray: oset = Convert.FromBase64String((string)v); break;

                case JsonDataType.List:
                    if (pi.TypeInfo.CollectionName != null)
                    {
                        goto default;
                    }
                    oset = CreateList((JsonArray)v, pi.TypeInfo, pi.CanWrite && (m.IsClass || m.IsStruct) ? null : m.Getter(o));
                    break;

                case JsonDataType.Object: oset = v; break;

                default:
                    if (pi.TypeInfo.DeserializeMethod != null)
                    {
                        oset = pi.TypeInfo.DeserializeMethod(this, ji._Value, pi.TypeInfo);
                        goto SET_VALUE;
                    }
                    if ((m.IsClass || m.IsStruct) && v is JsonDict)
                    {
                        oset = CreateObject((JsonDict)v, pi.TypeInfo, m.Getter(o));
                    }

                    else if (v is JsonArray)
                    {
                        oset = CreateArray((JsonArray)v, _manager.GetSerializationInfo(typeof(object[])));
                    }

                    else if (m.IsValueType)
                    {
                        oset = ChangeType(v, m.ChangeType);
                    }

                    else
                    {
                        oset = v;
                    }

                    break;
                }
SET_VALUE:
                ji.Value = oset;
                if (si != null)
                {
                    if (si.OnDeserializing(o, ji) == false)
                    {
                        continue;
                    }
                }
                if (m.Setter != null)
                {
                    //try {
                    o = m.Setter(o, ji.Value);
                    //}
                    //catch (InvalidCastException) {
                    //	if (_manager.SetDefaultForMismatchedProperty) {
                    //		o = m.Setter(o, m.IsValueType ? System.Runtime.Serialization.FormatterServices.GetUninitializedObject(m.MemberType) : null);
                    //		Console.WriteLine("Error when setting " + m.MemberName);
                    //		continue;
                    //	}
                    //	throw;
                    //}
                }
            }
            if (si != null)
            {
                si.OnDeserialized(o);
            }
            return(o);
        }