2

我曾经JSON.stringify()在 cookie 中存储一个带有布尔值的整数键的 javascript 关联数组,例如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."}

我猜在这种情况下无法进行反序列化?

4

1 回答 1

0

Frits van Campen 找到了丢失的部分。我编写了以下扩展方法,可以轻松地在 C# 中检索 cookie 值。同时设置urlDecodefromJsontrue对象将被成功反序列化。

/// <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;
}
于 2012-04-27T19:57:45.900 回答