当前位置: 首页>>代码示例>>C#>>正文


C# JavaScriptSerializer.Deserialize方法代码示例

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


在下文中一共展示了JavaScriptSerializer.Deserialize方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。

示例1: 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

示例2: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        String str = HttpContext.Current.Request.Url.AbsoluteUri;
        String userId = str.Substring(str.LastIndexOf("=")+1);
        try
        {
            String filename = Server.MapPath("~/User_Data/" + userId + ".js");
            String jsonData = File.ReadAllText(filename);

            JavaScriptSerializer serializer = new JavaScriptSerializer();
            RegData data = serializer.Deserialize<RegData>(jsonData);

            name.Text = data.name;
            userid.Text = userId;

            String imageurl = "~/User_Images/" + userId + ".jpg";
            userImage.ImageUrl = imageurl;


        }
        catch (IOException exn)
        {
            Response.Redirect("Error.aspx?userid=" + userId + "&errid=lookup");
        }
    }
开发者ID:bujixd,项目名称:asp.net,代码行数:25,代码来源:Details.aspx.cs

示例3: SubmitSecretQuestion

    public void SubmitSecretQuestion(object sender, EventArgs e)
    {
        string centGetUserAttributes = Session["UserAttributes"].ToString();
        var jssGetUserAttributes = new JavaScriptSerializer();
        Dictionary<string, dynamic> centGetUserAttribrutes_Dict = jssGetUserAttributes.Deserialize<Dictionary<string, dynamic>>(centGetUserAttributes);

        string strUuid = centGetUserAttribrutes_Dict["Result"]["Uuid"];

        string strSetQuestionJSON = @"{""ID"":""" + strUuid + @""",""securityquestion"":""" + SecretQuestion.Text + @""",""questionanwser"":""" + SecretAnswer.Text + @"""}";

        Centrify_API_Interface centSetQuestion = new Centrify_API_Interface().MakeRestCall(Session["NewPodURL"].ToString() + CentSetSecurityQuestionURL, strSetQuestionJSON);
        var jssSetQuestion = new JavaScriptSerializer();
        Dictionary<string, dynamic> centSetQuestion_Dict = jssSetQuestion.Deserialize<Dictionary<string, dynamic>>(centSetQuestion.returnedResponse);

        if (centSetQuestion_Dict["success"].ToString() != "True")
        {
            FailureText.Text = centSetQuestion_Dict["success"].ToString();
            ErrorMessage.Visible = true;
        }
        else
        {
            SecretQuestion_Div.Visible = false;
            AccountOverview.Visible = true;
        }
    }
开发者ID:erajsiddiqui,项目名称:CentrifyAPIExamples_APIDemoWebsite,代码行数:25,代码来源:MyAccount.aspx.cs

示例4: 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

示例5: sendSMSReq

    public MtSmsResp sendSMSReq(MtSmsReq mtSmsReq)
    {
        StreamWriter requestWriter;
        MtSmsResp mtSmsResp=null;

        try
        {
            var webRequest = System.Net.WebRequest.Create(url) as HttpWebRequest;

            if (webRequest != null)
            {
                webRequest.Method = "POST";
                webRequest.ContentType = "application/json";
                using (requestWriter = new StreamWriter(webRequest.GetRequestStream()))
                {
                    requestWriter.Write(mtSmsReq.ToString());
                }
            }

            HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
            Stream responseStream = response.GetResponseStream();
            StreamReader responseReader = new StreamReader(responseStream);
            String jsonResponseString = responseReader.ReadToEnd();

            JavaScriptSerializer javascriptserializer = new JavaScriptSerializer();
            mtSmsResp = javascriptserializer.Deserialize<MtSmsResp>(jsonResponseString);
        }
        catch (Exception ex)
        {
            throw new SdpException(ex);
        }
        return mtSmsResp;
    }
开发者ID:SajithLakjaya,项目名称:Ideamart-C-Sharp-SMS-SDK,代码行数:33,代码来源:SmsSender.cs

示例6: 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

示例7: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        Object user = Session["userid"];
        if (user != null)
        {
            String userid = (String)user;
            try
            {
                String filename = Server.MapPath("~/User_Data/" + userid + ".js");
                String jsonData = File.ReadAllText(filename);

                JavaScriptSerializer serializer = new JavaScriptSerializer();
                RegData data = serializer.Deserialize<RegData>(jsonData);

                name.Text = data.name;
                Userid.Text = userid;
                userName.Text = data.userName;
                password.Text = data.password;
                userProfile.Text = data.userProfile;
                state.Text = data.state;
                politic.Text = data.politic;
                foreach (string interest in data.interests)
                {
                    interests.Text += interest+",";
                }
                String imageurl = "~/User_Images/" + userid + ".jpg";
                Image.ImageUrl = imageurl;
            }
            catch (IOException exn) {
                Response.Redirect("Error.aspx?userid=" + userid + "&errid=lookup");
            }
        }
        else {
            Response.Redirect("Login.aspx");
        }


        /*
        HttpCookie cookie = Request.Cookies.Get("Registration");
        if (cookie != null)
        {
            name.Text = cookie["name"];
            userName.Text = cookie["userName"];
            password.Text = cookie["password"];
            userProfile.Text = cookie["userProfile"];
            state.Text = cookie["state"];
            politic.Text = cookie["politic"];
            interests.Text = cookie["interests"];
        }
        else {
            name.Text = "<Undefined name>";
            userName.Text = "<Undefined user name>";
            password.Text = "<Undefined password>";
            userProfile.Text = "<Undefined user profile>";
            state.Text = "<Undefined state>";
            politic.Text = "<Undefined politic>";
            interests.Text = "<Undefined interests>";
        }
         * */
    }
开发者ID:bujixd,项目名称:asp.net,代码行数:60,代码来源:lookup.aspx.cs

示例8: Main

    public static void Main(string[] args)
    {
        // API Key, password and host provided as arguments
        if(args.Length != 3) {
          Console.WriteLine("Usage: ApplicantTracking <key> <password> <host>");
          Environment.Exit(1);
        }

        var API_Key = args[0];
        var API_Password = args[1];
        var host = args[2];

        var url = "https://" + host + "/remote/jobs/active.json";

        using (var wc = new WebClient()) {

        //Attach crendentials to WebClient header
        string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(API_Key + ":" + API_Password));
        wc.Headers[HttpRequestHeader.Authorization] = "Basic " + credentials;

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        var results = serializer.Deserialize<Job[]>(wc.DownloadString(url));

        foreach(var job in results) {
          //Print results
          Console.WriteLine(job.Title + " (" + job.URL + ")");
        }
          }
    }
开发者ID:applicant-tracking,项目名称:applicant_tracking_api,代码行数:30,代码来源:ApplicantTracking.cs

示例9: Page_Load

    /// <summary>
    /// This method called when the page is loaded into the browser. This method requests input stream and parses it to get message counts.
    /// </summary>
    /// <param name="sender">object, which invoked this method</param>
    /// <param name="e">EventArgs, which specifies arguments specific to this method</param>
    protected void Page_Load(object sender, EventArgs e)
    {

        System.IO.Stream stream = Request.InputStream;

        this.receivedDeliveryStatusFilePath = ConfigurationManager.AppSettings["ReceivedDeliveryStatusFilePath"];
        if (string.IsNullOrEmpty(this.receivedDeliveryStatusFilePath))
            this.receivedDeliveryStatusFilePath = "~\\DeliveryStatus.txt";

        string count = ConfigurationManager.AppSettings["NumberOfDeliveryStatusToStore"];
        if (!string.IsNullOrEmpty(count))
            this.numberOfDeliveryStatusToStore = Convert.ToInt32(count);

        if (null != stream)
        {
            byte[] bytes = new byte[stream.Length];
            stream.Position = 0;
            stream.Read(bytes, 0, (int)stream.Length);
            string responseData = Encoding.ASCII.GetString(bytes);

            JavaScriptSerializer serializeObject = new JavaScriptSerializer();
            DeliveryStatusNotification message = (DeliveryStatusNotification)serializeObject.Deserialize(responseData, typeof(DeliveryStatusNotification));

            if (null != message)
            {
                this.SaveMessage(message);
            }
        }
    }
开发者ID:cingo1,项目名称:ATT_APIPlatform_SampleApps,代码行数:34,代码来源:StatusListener.aspx.cs

示例10: Page_Load

    protected void Page_Load(object sender, EventArgs e)
    {
        int quoteId = Convert.ToInt32(Request.Params["quote_id"]);

        Quote quote = new Quote(quoteId);

        // Remove the old items from this quote
        quote.ClearItems();

        // Get the new quote items, will be a JSON array in the POST field
        string quoteItemsString = Request.Params["quote_items"];
        if ( String.IsNullOrEmpty(Request.Params["quote_items"]) || String.IsNullOrEmpty(Request.Params["quote_id"])){
            Response.StatusCode = 500;
            Response.End();
        }
        // Deserialise the JSON into QuoteItem objects and create each one (insert into DB)
        JavaScriptSerializer jsl = new JavaScriptSerializer();
        List<QuoteItem> quoteItems =(List<QuoteItem>)jsl.Deserialize(quoteItemsString, typeof(List<QuoteItem>));
        foreach (QuoteItem item in quoteItems)
            item.Create();

        // Get the quote and update the fields from the form on the ViewQuote page.
        quote.Revision++;
        quote.DiscountPercent = Convert.ToDouble(Request.Params["discount_percent"]);
        quote.DiscountPercent24 = Convert.ToDouble(Request.Params["discount_percent_24"]);
        quote.DiscountPercent36 = Convert.ToDouble(Request.Params["discount_percent_36"]);
        quote.DiscountPercentSetup = Convert.ToDouble(Request.Params["discount_percent_setup"]);
        quote.DiscountWritein = Convert.ToDouble(Request.Params["discount_writein"]);
        quote.Title = Request.Params["title"];
        quote.LastChange = DateTime.Now;
        quote.Save();
    }
开发者ID:tonybaloney,项目名称:No-More-Spreadsheets,代码行数:32,代码来源:SaveQuote.aspx.cs

示例11: GEOCodeAddress

 public static dynamic GEOCodeAddress(String Address)
 {
     var address = String.Format("http://maps.google.com/maps/api/geocode/json?address={0}&sensor=false", Address.Replace(" ", "+"));
     var result = new System.Net.WebClient().DownloadString(address);
     var jss = new JavaScriptSerializer();
     return jss.Deserialize<dynamic>(result);
 }
开发者ID:haithemaraissia,项目名称:Rental,代码行数:7,代码来源:Default2.aspx.cs

示例12: ProcessRequest

 public void ProcessRequest(HttpContext context)
 {
     MoSmsResp moSmsResp = null;
     string jsonString="";
     context.Response.ContentType = "application/json";
     try
     {
         byte[] PostData = context.Request.BinaryRead(context.Request.ContentLength);
         jsonString = Encoding.UTF8.GetString(PostData);
         JavaScriptSerializer json_serializer = new JavaScriptSerializer();
         MoSmsReq moSmsReq = json_serializer.Deserialize<MoSmsReq>(jsonString);
         moSmsResp = GenerateStatus(true);
         onMessage(moSmsReq);
     }
     catch (Exception)
     {
         moSmsResp = GenerateStatus(false);
     }
     finally
     {
         if (jsonString.Equals(""))
             context.Response.Write(APPLICATION_RUNING_MESSAGE);
         else
             context.Response.Write(moSmsResp.ToString());
     }
 }
开发者ID:SajithLakjaya,项目名称:Ideamart-C-Sharp-SMS-SDK,代码行数:26,代码来源:SmsListener.cs

示例13: 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

示例14: Should_register_converters_when_asked

        public void Should_register_converters_when_asked()
        {
            // Given
            var defaultSerializer = new JavaScriptSerializer();
            var configuration = new JsonConfiguration(Encoding.UTF8, new[] { new TestConverter() }, new[] { new TestPrimitiveConverter() }, false, false);

            // When
            var serializer = new JavaScriptSerializer(configuration, true, GlobalizationConfiguration.Default);

            var data =
                new TestData()
                {
                    ConverterData =
                        new TestConverterType()
                        {
                            Data = 42,
                        },

                    PrimitiveConverterData =
                        new TestPrimitiveConverterType()
                        {
                            Data = 1701,
                        },
                };

            const string ExpectedJSON = @"{""converterData"":{""dataValue"":42},""primitiveConverterData"":1701}";

            // Then
            serializer.Serialize(data).ShouldEqual(ExpectedJSON);

            serializer.Deserialize<TestData>(ExpectedJSON).ShouldEqual(data);
        }
开发者ID:uliian,项目名称:Nancy,代码行数:32,代码来源:JavaScriptSerializerFixture.cs

示例15: ProcessRequest

    public override void ProcessRequest(HttpContext context, Match match)
    {
        context.Response.Cache.SetCacheability(HttpCacheability.NoCache);

        // Environmental Setup
        PccConfig.LoadConfig("pcc.config");

        string origDocument = GetStringFromUrl(context, match, "DocumentID");

        JavaScriptSerializer serializer = new JavaScriptSerializer();

        // Perform an HTTP GET request to retrieve properties about the viewing session from PCCIS.
        // The properties will include an identifier of the source document that will be used below
        // to locate the name of file where the markups for the current document were written.
        string uriString = PccConfig.ImagingService + "/ViewingSession/u" + HttpUtility.UrlEncode(origDocument);
        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(uriString);
        request.Method = "GET";
        request.Headers.Add("acs-api-key", PccConfig.ApiKey);

        // Send request to PCCIS and get response
        HttpWebResponse response = (HttpWebResponse)request.GetResponse();
        string responseBody = null;
        using (StreamReader sr = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8))
        {
            responseBody = sr.ReadToEnd();
        }

        // Deserialize the JSON response into a new DocumentProperties instance, which will provide
        // the original document name (a local file name in this case) which was specified by this application
        // during the original POST of the document.
        ViewingSessionProperties viewingSessionProperties = serializer.Deserialize<ViewingSessionProperties>(responseBody);
        int i = 1;

        //location of the saved markup xmls. This could be on webserver or network storage or database.
        DirectoryInfo di = new DirectoryInfo(PccConfig.MarkupFolder);
        FileInfo[] rgFiles = di.GetFiles("*.xml");
        string documentMarkupId = string.Empty;
        StringBuilder sb = new StringBuilder();
        StringBuilder sb1 = new StringBuilder();
        char[] charsToTrim = { ','};

        viewingSessionProperties.origin.TryGetValue("documentMarkupId", out documentMarkupId);
        foreach (FileInfo fi in rgFiles)
        {
            if (fi.Name.Contains(documentMarkupId + "_" + viewingSessionProperties.attachmentIndex))
            {
                string fileName = fi.Name;
                fileName = fi.Name.Replace(documentMarkupId + "_" + viewingSessionProperties.attachmentIndex + "_", "").Replace(".xml", "");
                sb1.AppendFormat("{{\"ID\": \"{0}\", \"annotationName\": \"{1}\", \"annotationLabel\": \"{2}\"}},", i.ToString(), fi.Name, fileName);
                i++;
            }
        }

        sb1.ToString().TrimEnd(charsToTrim);
        sb.Append("{\"annotationFiles\":[");
        sb.Append(sb1.ToString().TrimEnd(charsToTrim));
        sb.Append("] }");
        context.Response.Write(sb.ToString());
    }
开发者ID:Mahendravv,项目名称:ACS-C-Sharp-Viewing-Sample,代码行数:59,代码来源:HTTPAnnotationList.cs


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