Beispiel #1
0
        public static SessionState FromJson(string json)
        {
            if (string.IsNullOrEmpty(json))
            {
                return(null);
            }
            try
            {
                SessionStateItem           item        = JsonConvert.DeserializeObject <SessionStateItem>(json);
                SessionStateItemCollection collections = new SessionStateItemCollection();

                SaveValue      objectValue = null;
                JsonSerializer serializer  = new JsonSerializer();
                StringReader   sr          = null;
                JsonTextReader tReader     = null;

                foreach (KeyValuePair <string, SaveValue> kvp in item.Dict)
                {
                    objectValue = kvp.Value as SaveValue;
                    if (objectValue.Value == null)
                    {
                        collections[kvp.Key] = null;
                    }
                    else
                    {
                        if (!IsValueType(objectValue.Type))
                        {
                            sr      = new StringReader(objectValue.Value.ToString());
                            tReader = new JsonTextReader(sr);
                            collections[kvp.Key] = serializer.Deserialize(tReader, objectValue.Type);
                        }
                        else
                        {
                            collections[kvp.Key] = objectValue.Value;
                        }
                    }
                }

                return(new SessionState(collections, null, item.Timeout));
            }
            catch
            {
                return(null);
            }
        }
Beispiel #2
0
        public string ToJson()
        {
            // 这里忽略_staticObjects这个成员。
            if (_sessionItems == null || _sessionItems.Count == 0)
            {
                return(null);
            }

            Dictionary <string, SaveValue> dict = new Dictionary <string, SaveValue>(_sessionItems.Count);

            NameObjectCollectionBase.KeysCollection keys = _sessionItems.Keys;
            string key;
            object objectValue = string.Empty;
            Type   type        = null;

            for (int i = 0; i < keys.Count; i++)
            {
                key         = keys[i];
                objectValue = _sessionItems[key];
                if (objectValue != null)
                {
                    type = objectValue.GetType();
                }
                else
                {
                    type = typeof(object);
                }
                dict.Add(key, new SaveValue {
                    Value = objectValue, Type = type
                });
            }

            SessionStateItem item = new SessionStateItem {
                Dict = dict, Timeout = this._timeout
            };

            return(JsonConvert.SerializeObject(item));
        }