use*_*748 5 c# json sharepoint-2013
我正在使用JQuery.Cookie将javascript对象存储为cookie值:
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: '/' });
Run Code Online (Sandbox Code Playgroud)
当我在firebug中调试时,cookie值的值似乎正确格式化:
{"主题":"疾病预防和管理","地点":"孵化场山诊所","ClassName":"我有糖尿病,我能吃什么?"}
我正在用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);
}
}
Run Code Online (Sandbox Code Playgroud)
我有一个Refiners类,用于序列化:
public class Refiners
{
public string Topic { get; set; }
public string ClassName { get; set; }
public string Location { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
但是,此代码会抛出"无效的JSON原语"错误.我无法弄清楚为什么这不起作用.一种可能性是它没有正确读取cookie.当我打印出cookie的值作为字符串时,我得到:
%7B%22Topic%22%3A%22Disease%20Prevention%20于是%20Management%22%2C%22Class%22%3A%22Childbirth%20%26%20Parenting%202013%22%2C%22Location%22%3A%22GHC%20East %20Clinic%22%7D
Gra*_*mas 12
出现URL编码,尝试使用(通过属性页面公开实例)的UrlDecode方法解码值:HtmlUtilityServer
var refiners = serializer.Deserialize<Refiners>(Server.UrlDecode(cookie.Value));
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2287 次 |
| 最近记录: |