我用JSON.stringify()
将带有布尔值的整数键的javascript关联数组存储在cookie中,例如var arr = {}; arr[9000001] = True;
。我可以在服务器上以以下格式查看字符串的值:%7B%229000001%22%3Atrue%2C%229000003%22%3Atrue%2C%229000006%22%3Atrue%2C%229000009%22%3Atrue%7D
其中第一个数字为9000001,第二个为9000003,依此类推。
我想使用Json.Net反序列化为Dictionary<long,bool>
或类似名称。我尝试以下
var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(cookieValue);
但得到以下异常
{"Unexpected character encountered while parsing value: %. Path '', line 0, position 0."}
我猜在这种情况下不可能进行反序列化?
最佳答案
弗里斯·范·坎彭(Frits van Campen)找到了失踪的一块。我编写了以下扩展方法,使在C#中检索cookie值变得容易。将urlDecode
和fromJson
都设置为true
,对象将成功反序列化。
/// <summary>
/// retrieve object from cookie
/// </summary>
/// <typeparam name="T">type of object</typeparam>
/// <param name="controller"></param>
/// <param name="cookieName">name of cookie</param>
/// <param name="urlDecode">true to enable url decoding of the string</param>
/// <param name="fromJson">true if the string in cookie is Json stringified</param>
/// <returns>object in the cookie, or default value of T if object does not exist</returns>
public static T GetFromCookie<T>(this Controller controller, string cookieName,
bool urlDecode = true, bool fromJson = false)
{
var cookie = controller.HttpContext.Request.Cookies[cookieName];
if (cookie == null) return default(T);
var value = cookie.Value;
if (urlDecode)
value = Uri.UnescapeDataString(value);
T result;
if (fromJson)
result = JsonConvert.DeserializeObject<T>(value);
else
result = (T)Convert.ChangeType(value, typeof(T));
return result;
}