本文整理汇总了C#中JavaScriptSerializer类的典型用法代码示例。如果您正苦于以下问题:C# JavaScriptSerializer类的具体用法?C# JavaScriptSerializer怎么用?C# JavaScriptSerializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
JavaScriptSerializer类属于命名空间,在下文中一共展示了JavaScriptSerializer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: SignIn
private static void SignIn(string loginName, object userData)
{
var jser = new JavaScriptSerializer();
var data = jser.Serialize(userData);
//创建一个FormsAuthenticationTicket,它包含登录名以及额外的用户数据。
var ticket = new FormsAuthenticationTicket(2,
loginName, DateTime.Now, DateTime.Now.AddDays(1), true, data);
//加密Ticket,变成一个加密的字符串。
var cookieValue = FormsAuthentication.Encrypt(ticket);
//根据加密结果创建登录Cookie
var cookie = new HttpCookie(FormsAuthentication.FormsCookieName, cookieValue)
{
HttpOnly = true,
Secure = FormsAuthentication.RequireSSL,
Domain = FormsAuthentication.CookieDomain,
Path = FormsAuthentication.FormsCookiePath
};
//在配置文件里读取Cookie保存的时间
double expireHours = Convert.ToDouble(ConfigurationManager.AppSettings["loginExpireHours"]);
if (expireHours > 0)
cookie.Expires = DateTime.Now.AddHours(expireHours);
var context = System.Web.HttpContext.Current;
if (context == null)
throw new InvalidOperationException();
//写登录Cookie
context.Response.Cookies.Remove(cookie.Name);
context.Response.Cookies.Add(cookie);
}
示例2: SerializeToJsonResponse
//will attempt to serialize an object of any type
public static Response SerializeToJsonResponse(dynamic input)
{
Nancy.Json.JavaScriptSerializer ser = new JavaScriptSerializer();
var response = (Response)ser.Serialize(input);
response.ContentType = "application/json";
return response;
}
示例3: GetData
void GetData()
{
IList<object> list = new List<object>();
for (var i = 0; i < 5; i++)
{
list.Add(new
{
id = i,
pid = -1,
name = "部门" + i,
date = DateTime.Now,
remark = "部门" + i + " 备注"
});
}
for (var i = 5; i < 10; i++)
{
list.Add(new
{
id = i,
pid = 1,
name = "部门1-" + i,
date = DateTime.Now
});
}
var griddata = new { Rows = list };
string s = new JavaScriptSerializer().Serialize(griddata);
Response.Write(s);
}
示例4: ObtenerUnidadNegocio
public static string ObtenerUnidadNegocio()
{
List<List<EntUnidadNegocio>> multilst = new BusQueja().ObtenerUnidadNegocio();
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
string sJSON = oSerializer.Serialize(multilst);
return sJSON;
}
示例5: Should_not_register_converters_when_not_asked
public void Should_not_register_converters_when_not_asked()
{
// Given
var defaultSerializer = new JavaScriptSerializer();
// When
var serializer = new JavaScriptSerializer(JsonConfiguration.Default, GlobalizationConfiguration.Default);
var data =
new TestData()
{
ConverterData =
new TestConverterType()
{
Data = 42,
},
PrimitiveConverterData =
new TestPrimitiveConverterType()
{
Data = 1701,
},
};
const string ExpectedJSON = @"{""converterData"":{""data"":42},""primitiveConverterData"":{""data"":1701}}";
// Then
serializer.Serialize(data).ShouldEqual(ExpectedJSON);
serializer.Deserialize<TestData>(ExpectedJSON).ShouldEqual(data);
}
示例6: GetTasks
public string GetTasks()
{
IList<Task> tasks = new List<Task>();
using(SqlConnection connection = new SqlConnection("Data Source=.\\SQLEXPRESS;AttachDbFilename=|DataDirectory|JonteDatabase.mdf;Integrated Security=True;Connect Timeout=30;User Instance=True") )
{
using (SqlCommand command = new SqlCommand("SELECT * FROM Tasks",connection))
{
connection.Open();
SqlDataReader reader = command.ExecuteReader();
while (reader.Read())
{
Task task = new Task();
task.ID = (int)reader["TaskID"];
task.Name = (string)reader["Name"];
task.Author = (string) reader["Author"];
task.Done = (bool) reader["Done"];
tasks.Add(task);
}
}
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
return serializer.Serialize(tasks);
}
示例7: ParsePayload
private static Dictionary<string, string> ParsePayload(string[] args)
{
int payloadIndex=-1;
for (var i = 0; i < args.Length; i++)
{
Console.WriteLine(args[i]);
if (args[i]=="-payload")
{
payloadIndex = i;
break;
}
}
if (payloadIndex == -1)
{
Console.WriteLine("Payload is empty");
Environment.Exit(0);
}
if (payloadIndex >= args.Length-1)
{
Console.WriteLine("No payload value");
Environment.Exit(0);
}
string json = File.ReadAllText(args[payloadIndex+1]);
var jss = new JavaScriptSerializer();
Dictionary<string, string> values = jss.Deserialize<Dictionary<string, string>>(json);
return values;
}
示例8: parseJson
public void parseJson(String HtmlResult)
{
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
dynamic obj = serializer.Deserialize(HtmlResult, typeof(object));
Console.WriteLine(obj.meta);
}
示例9: GetMegaCategorySetting
private void GetMegaCategorySetting()
{
AspxCommonInfo aspxCommonObj = new AspxCommonInfo();
aspxCommonObj.StoreID = GetStoreID;
aspxCommonObj.PortalID = GetPortalID;
aspxCommonObj.CultureName = GetCurrentCultureName;
JavaScriptSerializer json_serializer = new JavaScriptSerializer();
MegaCategoryController objCat = new MegaCategoryController();
MegaCategorySettingInfo megaCatSetting = objCat.GetMegaCategorySetting(aspxCommonObj);
if (megaCatSetting != null)
{
object obj = new {
ModeOfView = megaCatSetting.ModeOfView,
NoOfColumn = megaCatSetting.NoOfColumn,
ShowCatImage = megaCatSetting.ShowCategoryImage,
ShowSubCatImage = megaCatSetting.ShowSubCategoryImage,
Speed = megaCatSetting.Speed,
Effect = megaCatSetting.Effect,
EventMega = megaCatSetting.EventMega,
Direction = megaCatSetting.Direction,
MegaModulePath = MegaModulePath
};
Settings = json_serializer.Serialize(obj);
}
}
示例10: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
XDocument doc = null;
string result = null;
if (Request.QueryString["mode"] != null)
{
JavaScriptSerializer serializer = null;
doc = XDocument.Load(Server.MapPath("~/App_Data/Links.xml"));
switch (Request.QueryString["mode"])
{
case "1": // Load list
serializer = new JavaScriptSerializer();
var list = doc.Element("Links").Elements("Link").Select(lk => new { Id = lk.Attribute("id").Value, Title = lk.Element("Title").Value, Target = lk.Element("Target").Value });
result = serializer.Serialize(list);
break;
case "2": // Load a link
serializer = new JavaScriptSerializer();
var test = doc.Element("Links").Elements("Link").Where(lk => lk.Attribute("id").Value == Request.QueryString["id"]).Select(lk => new { Title = lk.Element("Title").Value, Target = lk.Element("Target").Value });
result = serializer.Serialize(test);
break;
}
Response.Clear();
Response.Write(result);
Response.End();
}
else if (Request.QueryString["id"] != null)
{
doc = XDocument.Load(Server.MapPath("~/App_Data/Links.xml"));
if (Request.QueryString["id"] == "0") // Add mode
{
string maxId = doc.Element("Links").Elements("Link").Max(tst => tst.Attribute("id").Value);
doc.Element("Links").Add(new XElement("Link", new XAttribute("id", maxId == null ? "1" : (short.Parse(maxId) + 1).ToString()),
new XElement("Title", Request.QueryString["tle"]),
new XElement("Target", Request.QueryString["trg"])));
doc.Save(Server.MapPath("~/App_Data/Links.xml"));
result = "1";
}
else // Edit mode
{
IEnumerable<XElement> element = doc.Element("Links").Elements("Link").Where(an => an.Attribute("id").Value == Request.QueryString["id"]);
foreach (XElement item in element)
{
item.Element("Title").Value = Request.QueryString["tle"];
item.Element("Target").Value = Request.QueryString["trg"];
doc.Save(Server.MapPath("~/App_Data/Links.xml"));
result = "1";
}
}
Response.Clear();
Response.Write(result);
Response.End();
}
}
}
示例11: ExecuteResult
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (string.IsNullOrEmpty(this.ContentType))
{
response.ContentType = this.ContentType;
}
else
{
response.ContentType = "application/json";
}
if (this.ContentEncoding != null)
{
response.ContentEncoding = this.ContentEncoding;
}
if (this.Data != null)
{
JavaScriptSerializer jsSerializer = new JavaScriptSerializer();
string jsonString = jsSerializer.Serialize(Data);
MatchEvaluator matchEvaluator = new MatchEvaluator(this.ConvertJsonDateToDateString);
Regex reg = new Regex(@"\\/Date\((\d+)\)\\/");
jsonString = reg.Replace(jsonString, matchEvaluator);
response.Write(jsonString);
}
}
示例12: GetStartupScript
/// <summary>
/// Create startup script
/// </summary>
private string GetStartupScript()
{
JavaScriptSerializer sr = new JavaScriptSerializer();
string json = sr.Serialize(
new
{
headerIconId = headerIcon.ClientID,
btnLoginId = btnLogin.ClientID,
btnLoginShortcutId = btnLoginShortcut.ClientID,
btnLogoutId = btnLogout.ClientID,
btnSettingsId = btnSettings.ClientID,
loginShortcutWrapperId = loginShortcutWrapper.ClientID,
lblNotificationNumberId = lblNotificationNumber.ClientID,
ulActiveRequestsId = ulActiveRequests.ClientID,
ulNewRequestsId = ulNewRequests.ClientID,
lnkNewRequestsId = lnkNewRequests.ClientID,
lblNewRequestsId = lblNewRequests.ClientID,
resRoomNewMessagesFormat = ResHelper.GetString("chat.support.roomnewmessages"),
resNewRequestsSingular = ResHelper.GetString("chat.support.newrequestssingular"),
resNewRequestsPlural = ResHelper.GetString("chat.support.newrequestsplural"),
settingsUrl = URLHelper.GetAbsoluteUrl("~/CMSModules/Chat/Pages/ChatSupportSettings.aspx"),
notificationManagerOptions = new
{
soundFileRequest = ChatHelper.EnableSoundSupportChat ? ResolveUrl("~/CMSModules/Chat/CMSPages/Sound/Chat_notification.mp3") : String.Empty,
soundFileMessage = ChatHelper.EnableSoundSupportChat ? ResolveUrl("~/CMSModules/Chat/CMSPages/Sound/Chat_message.mp3") : String.Empty,
notifyTitle = ResHelper.GetString("chat.general.newmessages")
}
}
);
return String.Format("$cmsj(function (){{ new ChatSupportHeader({0}); }});", json);
}
示例13: CovertCategoryDataTableToJSON
/// <summary>
/// The ConvertTourDataTableTOJson method converts a filled data table into a
/// JSON string to be saved as a text file by the caller.
/// </summary>
public string CovertCategoryDataTableToJSON(DataTable parFilledDataTable)
{
//Convert DataTable to List collection of Transfer Objects
List<TO_POI_Cateogry> items = new List<TO_POI_Cateogry>();
foreach (DataRow row in parFilledDataTable.Rows)
{
string ID = Convert.ToString(row["Category_Code"]);
string title = Convert.ToString(row["Category_Name"]);
string fileName = "Category_" + ID + ".js";
TO_POI_Cateogry itemTransferObject = new TO_POI_Cateogry(ID, title, fileName);
items.Add(itemTransferObject);
}
//Create JSON-formatted string
JavaScriptSerializer oSerializer = new JavaScriptSerializer();
string JSONString = oSerializer.Serialize(items);
//add in return JSONString when taking out PrettyPrint
return JSONString;
////Format json string
//string formattedJSONString = JsonFormatter.PrettyPrint(JSONString);
// return formattedJSONString;
}
示例14: student_info
public static string student_info()
{
JavaScriptSerializer jss = new JavaScriptSerializer();
stu_Manage stuManage = new stu_Manage();
return jss.Serialize(stuManage.stu_Info(sno));
//return string.Format("欢迎你{0} {1}", sno, sname);
}
示例15: Deserialize
public override object Deserialize(IDictionary<string, object> dictionary, Type type, JavaScriptSerializer serializer)
{
if (dictionary == null)
throw new ArgumentNullException("dictionary");
return type == typeof(object) ? new DynamicJsonObject(dictionary) : null;
}