2012-04-27 92 views
2

我用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,依此類推。反序列化JavaScript的關聯數組到C#字典與Json.Net

我想用Json.Net反序列化到Dictionary<long,bool>或相似。我嘗試以下

var result = JsonConvert.DeserializeObject<Dictionary<string, string>>(cookieValue); 

但出現以下情況例外

{"Unexpected character encountered while parsing value: %. Path '', line 0, position 0."} 

我猜反序列化是不可能在這種情況下?

+2

也許你需要先'urldecode'?我不知道它在C#中調用的是什麼。 – Halcyon 2012-04-27 19:43:55

+0

這就是答案。 'Uri.UnescapeDataString(cookieValue)' – Alex 2012-04-27 19:50:28

回答

0

弗裏茨麪包車坎彭找到了失落的一角。我編寫了以下擴展方法,可以很容易地在C#中檢索cookie值。將urlDecodefromJson都設置爲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; 
}