我正在将一个对象序列化成JSON字符串,以便将其存储在cookie中。该对象如下所示:
public class ShoppingCart
{
public List<ShoppingCartItem> Items { get; set; }
public ShoppingCart()
{
Items = new List<ShoppingCartItem>();
}
}
public class ShoppingCartItem
{
public enum ShoppingCartItemType
{
TypeOfItem,
AnotherTypeOfItem
}
public int Identifier { get; set; }
public ShoppingCartItemType Type { get; set; }
}
我希望能够从cookie中以JSON字符串的形式检索对象,并将其解码回ShoppingCart
类型的对象,使其项正确反序列化。
这是我用来实现此操作的代码:
public class CookieStore
{
public static void SetCookie(string key, object value, TimeSpan expires)
{
string valueToStore = Json.Encode(value);
HttpCookie cookie = new HttpCookie(key, valueToStore);
if (HttpContext.Current.Request.Cookies[key] != null)
{
var cookieOld = HttpContext.Current.Request.Cookies[key];
cookieOld.Expires = DateTime.Now.Add(expires);
cookieOld.Value = cookie.Value;
HttpContext.Current.Response.Cookies.Add(cookieOld);
}
else
{
cookie.Expires = DateTime.Now.Add(expires);
HttpContext.Current.Response.Cookies.Add(cookie);
}
}
public static object GetCookie(string key)
{
string value = string.Empty;
HttpCookie cookie = HttpContext.Current.Request.Cookies[key];
if (cookie != null)
{
value = cookie.Value;
}
return Json.Decode(value);
}
}
请注意,存储cookie的效果非常好。它有正确的名称,JSON字符串看起来很不错;这里是一个例子:
{"Items":[{"Identifier":1,"Type":1}]}
问题是,当我尝试反序列化时,我认为它没有识别到数组实际上是
List<ShoppingCartItem>
,因此我最终得到的是一个 ShoppingCart
类的实例,其中 Items 属性设置为空的 List<ShoppingCartItem>
。有人知道我该如何解决这个问题吗?如果可能的话,我更愿意继续使用标准的
System.Web.Helpers.Json
,但如果需要更强大的 JSON 序列化器,我也愿意尝试。
ShoppingCart
的实例?如果是这样,那么明确地转换类型,即Json.Decode<List<ShoppingCart>>(value)
,应该可以解决问题。 - Mark Miller