本文整理汇总了C#中System.Web.Script.Serialization.JavaScriptSerializer类的典型用法代码示例。如果您正苦于以下问题:C# Script.Serialization.JavaScriptSerializer类的具体用法?C# Script.Serialization.JavaScriptSerializer怎么用?C# Script.Serialization.JavaScriptSerializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
Script.Serialization.JavaScriptSerializer类属于System.Web命名空间,在下文中一共展示了Script.Serialization.JavaScriptSerializer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: ExecuteResult
public override void ExecuteResult(ControllerContext context)
{
if (context == null)
{
throw new ArgumentNullException("context");
}
HttpResponseBase response = context.HttpContext.Response;
if (!string.IsNullOrEmpty(ContentType))
{
response.ContentType = ContentType;
}
else
{
response.ContentType = "application/json";
}
if (ContentEncoding != null)
{
response.ContentEncoding = ContentEncoding;
}
if (Data != null)
{
var enumerable = Data as IEnumerable;
if (enumerable != null)
{
Data = new {d = enumerable};
}
var serializer = new JavaScriptSerializer();
response.Write(serializer.Serialize(Data));
}
}
示例2: Main
static void Main(string[] args)
{
StreamReader sr = new StreamReader(Console.OpenStandardInput());
string input = sr.ReadToEnd();
sr.Dispose();
JavaScriptSerializer ser = new JavaScriptSerializer();
dynamic json = ser.DeserializeObject(input);
for (int i = 1; i < json.Length; i++)
{
dynamic block = json[i];
string blockType = block[0];
Dictionary<string, object> blockAttr = block[1];
for (int j = 2; j < block.Length; j++)
{
dynamic span = block[j];
string spanType = span[0];
string text = span[1];
Console.Write(text);
}
Console.WriteLine();
Console.WriteLine();
}
}
示例3: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
// Ensure config file is setup
if (!File.Exists(Server.MapPath(ConfigFile)))
{
throw new Exception("Config file not found");
}
var serializer = new JavaScriptSerializer();
string jsonText = System.IO.File.ReadAllText(Server.MapPath(ConfigFile));
Config = serializer.Deserialize<Dictionary<string, dynamic>>(jsonText);
if (Config["username"] == "your_api_username")
{
throw new Exception("Please configure your username, secret and site_id");
}
ObjHd4 = new Hd4(Request, ConfigFile);
// Models example : Get a list of all models for a specific vendor
Response.Write("<h1>Nokia Models</h1><p>");
if (ObjHd4.DeviceModels("Nokia"))
{
Response.Write(ObjHd4.GetRawReply());
}
else
{
Response.Write(ObjHd4.GetError());
}
Response.Write("</p>");
}
示例4: GetMenu
/// <summary>
/// 获取当前菜单,如果菜单不存在,将返回null
/// </summary>
/// <param name="accessToken"></param>
/// <returns></returns>
public static GetMenuResult GetMenu(string accessToken)
{
var url = string.Format("https://api.weixin.qq.com/cgi-bin/menu/get?access_token={0}", accessToken);
var jsonString = HttpUtility.RequestUtility.HttpGet(url, Encoding.UTF8);
//var finalResult = GetMenuFromJson(jsonString);
GetMenuResult finalResult;
JavaScriptSerializer js = new JavaScriptSerializer();
try
{
var jsonResult = js.Deserialize<GetMenuResultFull>(jsonString);
if (jsonResult.menu == null || jsonResult.menu.button.Count == 0)
{
throw new WeixinException(jsonResult.errmsg);
}
finalResult = GetMenuFromJsonResult(jsonResult);
}
catch (WeixinException ex)
{
finalResult = null;
}
return finalResult;
}
示例5: SearchBooks
public string SearchBooks(string paramList)
{
JavaScriptSerializer jsonObj = new JavaScriptSerializer();
string[] parameters = paramList.Split(',');
string genre = "";
var publisher = "";
if (parameters.Length > 0)
{
genre = parameters[0];
}
if (parameters
.Length > 0)
{
publisher = parameters[1];
}
var books = new List<Book>();;
try
{
var booksDAL = new BookSearchDAL();
books = booksDAL.SearchBooksAndUpdateHits(genre, publisher);
}
catch (Exception)
{
}
return (jsonObj.Serialize(books));
}
示例6: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
LoadCategoryDiv();
string IPAdd = string.Empty;
IPAdd = Request.ServerVariables["HTTP_X_FORWARDED_FOR"];
if (string.IsNullOrEmpty(IPAdd))
{
IPAdd = Request.ServerVariables["REMOTE_ADDR"];
//lblIPBehindProxy.Text = IPAdd;
}
string JSON = GetLocation(IPAdd);
if (!string.IsNullOrWhiteSpace(JSON))
{
JavaScriptSerializer Serializer = new JavaScriptSerializer();
dynamic dynamicResult = Serializer.Deserialize<dynamic>(JSON);
//Response.Write(dynamicResult["countryName"].ToString());
//Response.Write(dynamicResult["countryCode"].ToString());
//Response.Write(dynamicResult["city"].ToString());
//Response.Write(dynamicResult["region"].ToString());
//Response.Write(dynamicResult["latitude"].ToString());
//Response.Write(dynamicResult["longitude"].ToString());
currentLocation.InnerText = string.Format(" / Country: {0}/{1}, City: {2}/{3} ",
dynamicResult["countryName"].ToString(), dynamicResult["countryCode"].ToString(), dynamicResult["city"].ToString(),
dynamicResult["region"].ToString());
strcurrentLocation = string.Format(" / Country: {0}/{1}, City: {2}/{3} ",
dynamicResult["countryName"].ToString(), dynamicResult["countryCode"].ToString(), dynamicResult["city"].ToString(),
dynamicResult["region"].ToString());
if (Session["Location"] == null)
Session.Add("Location", dynamicResult["city"].ToString());
}
else
{
string userHostIpAddress = IPAdd; // "117.197.193.243";
IPAddress ipAddress;
//Response.Write("<script>alert('"+userHostIpAddress+"')</Script>");
if (userHostIpAddress == "::1")
{
userHostIpAddress = "117.197.193.243";
}
if (IPAddress.TryParse(userHostIpAddress, out ipAddress))
{
string country = ipAddress.Country(); // return value: UNITED STATES
string iso3166TwoLetterCode = ipAddress.Iso3166TwoLetterCode(); // return value: US
currentLocation.InnerText = string.Format("Country: {0} / Location: {1} ", country, iso3166TwoLetterCode);
strcurrentLocation = string.Format("Country: {0} / Location: {1} ", country, iso3166TwoLetterCode);
if (Session["Location"] == null)
Session.Add("Location", iso3166TwoLetterCode);
//Session.Add("Location", "wyoming");
}
}
}
示例7: Login
public ActionResult Login()
{
var lists = ManageNodes();
var serializer = new JavaScriptSerializer();
ViewBag.Nodes = serializer.Serialize(lists);
return View();
}
示例8: getObjects
/// <summary>
/// Parses the JSON data returned by the 0/data/getTrades.php method
/// </summary>
public static List<MtGoxTrade> getObjects(string jsonDataStr)
{
List<MtGoxTrade> tradeList = new List<MtGoxTrade>();
string json = jsonDataStr;
var serializer = new JavaScriptSerializer();
serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
dynamic obj = serializer.Deserialize(json, typeof(object));
for (int i = 0; i < obj.Length; i++)
{
MtGoxTrade trade = new MtGoxTrade();
trade.date = obj[i].date;
trade.price = Double.Parse(obj[i].price);
trade.amount = Double.Parse(obj[i].amount);
trade.price_int = Int64.Parse(obj[i].price_int);
trade.amount_int = Int64.Parse(obj[i].amount_int);
trade.tid = obj[i].tid;
if (Enum.IsDefined(typeof(MtGoxCurrencySymbol), obj[i].price_currency))
trade.price_currency = (MtGoxCurrencySymbol)Enum.Parse(typeof(MtGoxCurrencySymbol), obj[i].price_currency, true);
trade.item = obj[i].item;
if (Enum.IsDefined(typeof(MtGoxTradeType), obj[i].trade_type))
trade.trade_type = (MtGoxTradeType)Enum.Parse(typeof(MtGoxTradeType), obj[i].trade_type, true);
trade.primary = obj[i].primary;
tradeList.Add(trade);
if (i > 100)
break;
}
return tradeList;
}
示例9: loadVentas
public void loadVentas()
{
List<Venta> lv = new List<Venta>();
var javaScriptSerializer = new JavaScriptSerializer();
string jsonVentas = "";
Ventas serv = new Ventas();
serv.Url = new Juddi().getServiceUrl("Ventas");
jsonVentas = serv.getVentas((int)Session["Id"]);
lv = javaScriptSerializer.Deserialize<List<Venta>>(jsonVentas);
DataTable dt = new DataTable();
dt.Columns.AddRange(new DataColumn[7] {
new DataColumn("id", typeof(int)),
new DataColumn("tipo", typeof(string)),
new DataColumn("autor",typeof(string)),
new DataColumn("estado",typeof(string)),
new DataColumn("fechafin",typeof(string)),
new DataColumn("pujamax",typeof(int)),
new DataColumn("pujar",typeof(string))
});
for (int i = 0; i < lv.Count; i++)
{
dt.Rows.Add(lv[i].id, lv[i].tipo, lv[i].autor, lv[i].estado, lv[i].fecha_F, lv[i].precio, "Pujar");
}
GridView1.DataSource = dt;
GridView1.DataBind();
}
示例10: CreateIncident
private void CreateIncident()
{
WebClient client = new WebClient();
client.Headers[HttpRequestHeader.Accept] = "application/json";
client.Headers[HttpRequestHeader.ContentType] = "application/json";
client.UploadStringCompleted += (object source, UploadStringCompletedEventArgs e) =>
{
if (e.Error != null || e.Cancelled)
{
Console.WriteLine("Error" + e.Error);
Console.ReadKey();
}
};
JavaScriptSerializer js = new JavaScriptSerializer();
TriggerDetails triggerDetails = new TriggerDetails(Component, Details);
var detailJson = js.Serialize(triggerDetails);
//Alert name should be unique for each alert - as alert name is used as incident key in pagerduty.
string key = ConfigurationManager.AppSettings["PagerDutyServiceKey"];
if (!string.IsNullOrEmpty(EscPolicy))
{
key = ConfigurationManager.AppSettings["PagerDutySev1ServiceKey"];
}
if (string.IsNullOrEmpty(key))
{
key = ConfigurationManager.AppSettings["PagerDutyServiceKey"];
}
Trigger trigger = new Trigger(key,AlertName,AlertSubject,detailJson);
var triggerJson = js.Serialize(trigger);
client.UploadString(new Uri("https://events.pagerduty.com/generic/2010-04-15/create_event.json"), triggerJson);
}
示例11: GetDealClosingCostTypesFromDeepBlue
public static List<DeepBlue.Models.Entity.DealClosingCostType> GetDealClosingCostTypesFromDeepBlue(CookieCollection cookies)
{
// Admin/DealClosingCostTypeList?pageIndex=1&pageSize=5000&sortName=Name&sortOrder=asc
List<DeepBlue.Models.Entity.DealClosingCostType> dealClosingCostTypes = new List<DeepBlue.Models.Entity.DealClosingCostType>();
// Send the request
string url = HttpWebRequestUtil.GetUrl("Admin/DealClosingCostTypeList?pageIndex=1&pageSize=5000&sortName=Name&sortOrder=asc");
HttpWebResponse response = HttpWebRequestUtil.SendRequest(url, null, false, cookies, false, HttpWebRequestUtil.JsonContentType);
if (response.StatusCode == System.Net.HttpStatusCode.OK) {
using (Stream receiveStream = response.GetResponseStream()) {
// Pipes the stream to a higher level stream reader with the required encoding format.
using (StreamReader readStream = new StreamReader(receiveStream, Encoding.UTF8)) {
string resp = readStream.ReadToEnd();
if (!string.IsNullOrEmpty(resp)) {
JavaScriptSerializer js = new JavaScriptSerializer();
FlexigridData flexiGrid = (FlexigridData)js.Deserialize(resp, typeof(FlexigridData));
foreach (Helpers.FlexigridRow row in flexiGrid.rows) {
DeepBlue.Models.Entity.DealClosingCostType dealClosingType = new DeepBlue.Models.Entity.DealClosingCostType();
dealClosingType.DealClosingCostTypeID = Convert.ToInt32(row.cell[0]);
dealClosingType.Name = Convert.ToString(row.cell[1]);
dealClosingCostTypes.Add(dealClosingType);
}
}
else {
}
response.Close();
readStream.Close();
}
}
}
return dealClosingCostTypes;
}
示例12: Execute
public override void Execute(RequestContext context)
{
JavaScriptSerializer jss = new JavaScriptSerializer();
var json = jss.Serialize(paraObj);
context.HttpContext.Response.Write(json);
context.HttpContext.Response.ContentType = "application/json";
}
示例13: HandleCommand
public string HandleCommand(string commandId, string body) {
var serializer = new JavaScriptSerializer();
switch (commandId) {
case GetTestCasesCommand:
IProjectEntry projEntry;
if (_analyzer.TryGetProjectEntryByPath(body, out projEntry)) {
var testCases = GetTestCases(projEntry);
List<object> res = new List<object>();
foreach (var test in testCases) {
var item = new Dictionary<string, object>() {
{ Serialize.Filename, test.Filename },
{ Serialize.ClassName, test.ClassName },
{ Serialize.MethodName, test.MethodName },
{ Serialize.StartLine, test.StartLine},
{ Serialize.StartColumn, test.StartColumn},
{ Serialize.EndLine, test.EndLine },
{ Serialize.Kind, test.Kind.ToString() },
};
res.Add(item);
}
return serializer.Serialize(res.ToArray());
}
break;
}
return "";
}
示例14: MakeRequest
public static string MakeRequest(string url, object data) {
var ser = new JavaScriptSerializer();
var serialized = ser.Serialize(data);
HttpWebRequest request = (HttpWebRequest)WebRequest.Create(url);
request.Method = "POST";
//request.ContentType = "application/json; charset=utf-8";
//request.ContentType = "text/html; charset=utf-8";
request.ContentType = "application/x-www-form-urlencoded";
request.ContentLength = serialized.Length;
/*
StreamWriter writer = new StreamWriter(request.GetRequestStream());
writer.Write(serialized);
writer.Close();
var ms = new MemoryStream();
request.GetResponse().GetResponseStream().CopyTo(ms);
*/
//alternate method
ASCIIEncoding encoding = new ASCIIEncoding();
byte[] byte1 = encoding.GetBytes(serialized);
Stream newStream = request.GetRequestStream();
newStream.Write(byte1, 0, byte1.Length);
newStream.Close();
return serialized;
}
示例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;
}