I'm serialising an object into a JSON string in order to store it in a cookie. The object looks like this:
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; }
}
I would then like to be able to retrieve the object from the cookie as a JSON string, and decode it back into an object of type ShoppingCart
, with its items correctly deserialised.
This is the code I'm using to do this:
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);
}
}
Note that storing the cookie works beautifully. It has the correct name, and the JSON string looks good to me; here's an example:
{"Items":[{"Identifier":1,"Type":1}]}
The problem is, when I try to deserialise this, I think it's not recognising that the array is actually a List<ShoppingCartItem>
and so I end up with an instance of the ShoppingCart
class with the Items property set to an empty List<ShoppingCartItem>
.
Does anyone know how I can make this work? I'd prefer to continue using the standard System.Web.Helpers.Json
for this if possible, but if a more robust JSON serialiser is required I'm willing to do that.
>(value)`, should solve the problem.
– Mark Miller Jun 11 '15 at 03:58