2013-07-17 67 views
5
原始閱讀

我使用JQuery.Cookie存儲JavaScript對象作爲cookie值:C#無效JSON從餅乾

var refinerData = {}; 
// Read in the current cookie if it exists: 
if ($.cookie('RefinerData') != null) { 
    refinerData = JSON.parse($.cookie('RefinerData')); 
} 
// Set new values based on the category and filter passed in 
switch(category) 
{ 
    case "topic": 
     refinerData.Topic = filterVal; 
     break; 
    case "class": 
     refinerData.ClassName = filterVal; 
     break; 
    case "loc": 
     refinerData.Location = filterVal; 
     break; 
}  
// Save the cookie: 
$.cookie('RefinerData', JSON.stringify(refinerData), { expires: 1, path: '/' }); 

當我在Firebug調試,cookie值的價值似乎被格式化正確:

{「主題」:「疾病預防與管理」,「位置」:「孵化山診所」,「類名」:「我有糖尿病,我能吃」}

我m在C#中編寫一個SharePoint Web部件來讀取Cookie並解析它:

 protected void Page_Load(object sender, EventArgs e) 
    { 
     HttpCookie cookie = HttpContext.Current.Request.Cookies["RefinerData"]; 
     if (cookie != null) 
     { 
      string val = cookie.Value; 
      // Deserialize JSON cookie: 
      JavaScriptSerializer serializer = new JavaScriptSerializer(); 
      var refiners = serializer.Deserialize<Refiners>(cookie.Value); 
      output.AppendLine("Deserialized Topic = " + refiners.Topic); 
      output.AppendLine("Cookie exists: " + val); 
     } 
    } 

我有一個煉油類序列化到:

public class Refiners 
{ 
    public string Topic { get; set; } 
    public string ClassName { get; set; } 
    public string Location { get; set; } 
} 

然而,這個代碼拋出一個 「無效的JSON原始」 的錯誤。我無法弄清楚爲什麼這不起作用。一種可能性是它沒有正確讀取cookie。當我打印出cookie的價值作爲一個字符串,我得到:

%7B%22Topic%22%3A%22Disease%20Prevention%20and%20Management%22%2C%22Class%22%3A%22Childbirth%20 %26%20Parenting%202013%22%2C%22Location%22%3A%22GHC%20East%20Clinic%22%7D

回答

12

顯示URL編碼,嘗試使用HtmlUtilityUrlDecode方法(值進行解碼,其一個實例的通過翻閱Server屬性暴露):

var refiners = serializer.Deserialize<Refiners>(Server.UrlDecode(cookie.Value)); 
+2

是的,謝謝!那工作。我不得不稍微調整一下Server.UrlDecode,因爲它是一個共享點Web部件,但它工作起來很奇妙: var refiners = serializer.Deserialize (HttpContext.Current.Server.UrlDecode(cookie.Value)); – user1231748

+0

@ user1231748當然,我應該給你的詳細信息來訪問靜態引用,我的壞。很高興你得到它。 –

1

我想你需要之前,反序列化的cookie進行解碼。嘗試使用;

Refiners refiners = serializer.Deserialize<Refiners>(Server.UrlDecode(cookie.Value));