• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C# JavaScriptSerializer类代码示例

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

本文整理汇总了C#中JavaScriptSerializer的典型用法代码示例。如果您正苦于以下问题:C# JavaScriptSerializer类的具体用法?C# JavaScriptSerializer怎么用?C# JavaScriptSerializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。



JavaScriptSerializer类属于命名空间,在下文中一共展示了JavaScriptSerializer类的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的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);
    }
开发者ID:monkinone,项目名称:OrderPrinnt,代码行数:33,代码来源:Login.aspx.cs


示例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;
 }
开发者ID:kevnls,项目名称:StockQuoteService,代码行数:8,代码来源:Utilities.cs


示例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);
    }
开发者ID:sorceryzzz,项目名称:House,代码行数:30,代码来源:tree2.aspx.cs


示例4: ObtenerUnidadNegocio

 public static string ObtenerUnidadNegocio()
 {
     List<List<EntUnidadNegocio>> multilst = new BusQueja().ObtenerUnidadNegocio();
     JavaScriptSerializer oSerializer = new JavaScriptSerializer();
     string sJSON = oSerializer.Serialize(multilst);
     return sJSON;
 }
开发者ID:revigres,项目名称:AjaxSon,代码行数:7,代码来源:Default.aspx.cs


示例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);
        }
开发者ID:uliian,项目名称:Nancy,代码行数:31,代码来源:JavaScriptSerializerFixture.cs


示例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);
    }
开发者ID:Tazer,项目名称:JsonSample,代码行数:25,代码来源:JonteService.cs


示例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;
    }
开发者ID:rajeshkp,项目名称:iron_worker_examples,代码行数:29,代码来源:worker101.cs


示例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);
 }
开发者ID:vnkv9,项目名称:MIDTERM,代码行数:7,代码来源:Searchinput.aspx.cs


示例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); 
     }
 }
开发者ID:xiaoxiaocoder,项目名称:AspxCommerce2.7,代码行数:25,代码来源:MegaCategorySetting.ascx.cs


示例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();
            }
        }
    }
开发者ID:BehnamAbdy,项目名称:Ajancy,代码行数:60,代码来源:Links.aspx.cs


示例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);
        }
    }
开发者ID:RockyMyx,项目名称:ASP.NetMvc-Bootstrap,代码行数:33,代码来源:CustomJsonResult.cs


示例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);
    }
开发者ID:kbuck21991,项目名称:kentico-blank-project,代码行数:37,代码来源:SupportChatHeader.ascx.cs


示例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;
    }
开发者ID:klhuffsmith1-catamount-wcu-edu,项目名称:SylvaTour,代码行数:31,代码来源:JSON_Utils.cs


示例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);
 }
开发者ID:inspire09,项目名称:System,代码行数:7,代码来源:student_edit.aspx.cs


示例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;
    }
开发者ID:chrispebble,项目名称:statuspanic,代码行数:7,代码来源:DynamicJsonConverter.cs


示例16: GetServiceItemSetting

 public void GetServiceItemSetting()
 {
     AspxCommonInfo aspxCommonObj = new AspxCommonInfo();
     aspxCommonObj.StoreID = StoreID;
     aspxCommonObj.PortalID = PortalID;
     aspxCommonObj.CultureName = CultureName;
     ServiceItemController objService = new ServiceItemController();
     JavaScriptSerializer json_serializer = new JavaScriptSerializer();
     List<ServiceItemSettingInfo> lstServiceSetting = objService.GetServiceItemSetting(aspxCommonObj);
     if (lstServiceSetting != null && lstServiceSetting.Count > 0)
     {
         foreach (var serviceSetting in lstServiceSetting)
         {
             object obj = new
             {
                 IsEnableService = serviceSetting.IsEnableService,
                 ServiceCategoryInARow = serviceSetting.ServiceCategoryInARow,
                 ServiceCategoryCount = serviceSetting.ServiceCategoryCount,
                 IsEnableServiceRss = serviceSetting.IsEnableServiceRss,
                 ServiceRssCount = serviceSetting.ServiceRssCount,
                 ServiceRssPage = serviceSetting.ServiceRssPage,
                 ServiceDetailsPage = serviceSetting.ServiceDetailsPage,
                 ServiceItemDetailPage = serviceSetting.ServiceItemDetailsPage,
                 BookAnAppointmentPage = serviceSetting.BookAnAppointmentPage,
                 AppointmentSuccessPage = serviceSetting.AppointmentSuccessPage
             };
             Settings = json_serializer.Serialize(obj);
         }
     }
 }
开发者ID:xiaoxiaocoder,项目名称:AspxCommerce2.7,代码行数:30,代码来源:ServiceItemSetting.ascx.cs


示例17: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        if (Session["Admin"] == null || Session["Admin"].ToString() != "1")
            Response.Redirect("login.aspx");
        if (Request.QueryString["id"] == null)
            Response.Redirect("AboutListing.aspx");
        id = Request.QueryString["id"].ToString();

        PageHeader = Util.GetTemplate("Admin_header");
        string json = Util.GetFileContent("data");
        var serializer = new JavaScriptSerializer();
        serializer.RegisterConverters(new[] { new DynamicJsonConverter() });
        obj = serializer.Deserialize(json, typeof(object));

        if (!IsPostBack)
        {
            bool exists = false;
            foreach (dynamic obj1 in obj["Portfolio"])
            {
                if (obj1["id"] == id)
                {
                    txtTitle.Text = obj1["title"];
                    txtDescription.Text = obj1["description"];
                    txtSiteLink.Text = obj1["sitelink"];
                    txtClient.Text = obj1["client"];
                    txtDate.Text = obj1["date"];
                    txtService.Text = obj1["service"];
                    imgImage.ImageUrl = "../" + obj1["image"];
                    exists = true;
                }
            }
            if(!exists)
                Response.Redirect("PortfolioListing.aspx");
        }
    }
开发者ID:RefractedPaladin,项目名称:Freelancer-Template,代码行数:35,代码来源:PortfolioEdit.aspx.cs


示例18: GetUserInfo

    public string GetUserInfo(string username, string password)
    {
        User user = new User();
        using (MySqlConnection conn = new MySqlConnection(Tools.connectionString()))
        {
            conn.Open();
            MySqlCommand cmd = new MySqlCommand("GetUserInfo",conn);
            cmd.CommandType = System.Data.CommandType.StoredProcedure;
            cmd.Parameters.AddWithValue("_userid", DBNull.Value);
            cmd.Parameters.AddWithValue("_username", username);
            cmd.Parameters.AddWithValue("_password", password);

            MySqlDataReader reader = cmd.ExecuteReader();

            if(reader.Read())
            {
                user.UserID = Convert.ToInt32(reader["UserID"]);
                user.UserName = reader["UserName"].ToString();
                user.Wallet.Amount = Convert.ToDouble(reader["Amount"]);
                user.Wallet.Refills = Convert.ToInt32(reader["Refills"]);
            }
        }

        JavaScriptSerializer js = new JavaScriptSerializer();
        string strJSON = js.Serialize(user);
        return strJSON;
    }
开发者ID:Agent89,项目名称:CodenameMMA,代码行数:27,代码来源:MMACode.cs


示例19: WriteResponseJSON

 protected void WriteResponseJSON(object response)
 {
     Response.Clear();
     Response.ContentType = "application/json";
     var jss = new JavaScriptSerializer();
     Response.Write(jss.Serialize(response));
 }
开发者ID:adunndevster,项目名称:jaxi,代码行数:7,代码来源:compile.aspx.cs


示例20: AddItemToList

 // Methods
 private static void AddItemToList(IList oldList, IList newList, Type elementType, JavaScriptSerializer serializer)
 {
     foreach (object obj2 in oldList)
     {
         newList.Add(ConvertObjectToType(obj2, elementType, serializer));
     }
 }
开发者ID:konglingjie,项目名称:arcgis-viewer-silverlight,代码行数:8,代码来源:ObjectConverter.cs



注:本文中的JavaScriptSerializer类示例整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C# Jid类代码示例发布时间:2022-05-24
下一篇:
C# JavaScriptPropertyId类代码示例发布时间:2022-05-24
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap