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


C# DataContractJsonSerializer.ReadObject方法代码示例

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


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

示例1: Button_Click

        private async void Button_Click(object sender, RoutedEventArgs e)
        {
            if (CountryPhoneCode.SelectedItem != null)
            {
                var _id = Guid.NewGuid().ToString("N");
                var _countryPhoneCode = (CountryPhoneCode.SelectedItem as Country).PhoneCode;
                var _countryName = (CountryPhoneCode.SelectedItem as Country).CountryName;
                var _name = FullName.Text;
                var _phoneNumber = PhoneNumber.Text;
                var _password = Password.Password;

                var client = new HttpClient()
                {
                    BaseAddress = new Uri("http://yochat.azurewebsites.net/chat/")
                };

                var json = await client.GetStringAsync("createuser?id=" + _id + "&fullName=" + _name + "&password=" + _password + "&phoneNumber=" + _phoneNumber + "&countryPhoneCode=" + _countryPhoneCode);

                var serializer = new DataContractJsonSerializer(typeof(User));
                var ms = new MemoryStream();
                var user = serializer.ReadObject(ms) as User;

                Frame.Navigate(typeof(MainPage), user);
            }
            else
            {
                MessageDialog dialog = new MessageDialog("Lütfen Ülkenizi Seçiniz!");
                await dialog.ShowAsync();
            }
        }
开发者ID:yavuzgedik,项目名称:Windows10_UWP,代码行数:30,代码来源:LoginPage.xaml.cs

示例2: GetChampion

        /// <summary>
        /// Looks up a champion with the specified id.
        /// </summary>
        /// <param name="region">The region to check</param>
        /// <param name="championId">id of the champion to look up</param>
        /// <remarks>Version 1.2</remarks>
        /// <returns></returns>
        public Champion GetChampion(int championId)
        {
            Champion championCall = new Champion();
            Champion staticChampionCall = new Champion();

            DataContractJsonSerializer jSerializer = new DataContractJsonSerializer(typeof(Champion));
            WebClient webClient = new WebClient();
            try
            {
                championCall = (Champion)jSerializer.ReadObject(webClient.OpenRead(String.Format("https://{0}.api.pvp.net/api/lol/{0}/v1.2/champion/{1}?api_key={2}", _region, championId, _apiKey)));
                staticChampionCall = (Champion)jSerializer.ReadObject(webClient.OpenRead(string.Format("https://{0}.api.pvp.net/api/lol/static-data/{0}/v1.2/champion/{1}?champData=all&api_key={2}", _region, championId, _apiKey)));

                staticChampionCall.Active = championCall.Active;
                staticChampionCall.BotEnabled = championCall.BotEnabled;
                staticChampionCall.BotMmEnabled = championCall.BotMmEnabled;
                staticChampionCall.FreeToPlay = championCall.FreeToPlay;
                staticChampionCall.RankedPlayEnabled = championCall.RankedPlayEnabled;

            }
            catch (WebException e)
            {
                throw;
            }
            return staticChampionCall;
        }
开发者ID:ZeroDonuts,项目名称:LeagueOfLegendsLibrary,代码行数:32,代码来源:InfoGrabber.cs

示例3: ChunkedUpload

        static void ChunkedUpload(string token,int size = 1024 * 1024, int parts = 10)
        {
            Util.RandomFile(size, "chunked.txt");
            string respHTML = Util.HttpPost("https://api.onedrive.com/v1.0/drive/root:/chunked.txt:/upload.createSession", "", token);
            DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(UploadSession));
            UploadSession task = (UploadSession)ser.ReadObject(new MemoryStream(Encoding.ASCII.GetBytes(respHTML)));

            byte[] data = File.ReadAllBytes("chunked.txt");
            int offset = int.Parse(task.nextExpectedRanges[0].Split(new char[] { '-' })[0]);
            while (offset < data.Length)
            {
                int uplen = Math.Min(size / parts, data.Length - offset);
                respHTML = Util.HttpPut(task.uploadUrl, token, data, offset, uplen,
                    "bytes " + offset + "-" + (offset + uplen - 1) + "/" + data.Length);
                if (offset + uplen < data.Length)
                {
                    UploadSession ttask = (UploadSession)ser.ReadObject(new MemoryStream(Encoding.ASCII.GetBytes(respHTML)));
                    offset = int.Parse(ttask.nextExpectedRanges[0].Split(new char[] { '-' })[0]);
                }
                else
                    offset = data.Length;
            }

            File.Delete("chunked.txt");
        }
开发者ID:tiancaihb,项目名称:CloudConnect-dev,代码行数:25,代码来源:HelloOnedrive.cs

示例4: GetLatest

		public List<Tweet> GetLatest( string p_Query, int p_Count = 100 ) {
			TwitterResults _TwitterResults;
			List<Tweet> _ReturnValue = new List<Tweet>();
			DataContractJsonSerializer _JsonSerializer = new DataContractJsonSerializer( typeof( TwitterResults ) );

			HttpWebRequest _Request = WebRequest.Create( string.Format( "{0}?q={1}&result_type=recent&count={2}", BASE_SEARCH_URL, p_Query, p_Count ) ) as HttpWebRequest;
			_Request.Headers.Add( "Authorization", string.Format( "Bearer {0}", Credentials.access_token ) );
			_Request.KeepAlive = false;
			_Request.Method = "GET";

			HttpWebResponse _Response = _Request.GetResponse() as HttpWebResponse;
			_TwitterResults = (TwitterResults)_JsonSerializer.ReadObject( _Response.GetResponseStream() );
			_ReturnValue.AddRange( _TwitterResults.statuses );

			while( !string.IsNullOrWhiteSpace( _TwitterResults.search_metadata.next_results ) ) {
				_Request = WebRequest.Create( string.Format( "{0}{1}", BASE_SEARCH_URL, _TwitterResults.search_metadata.next_results ) ) as HttpWebRequest;
				_Request.Headers.Add( "Authorization", string.Format( "Bearer {0}", Credentials.access_token ) );
				_Request.KeepAlive = false;
				_Request.Method = "GET";

				_Response = _Request.GetResponse() as HttpWebResponse;
				_TwitterResults = (TwitterResults)_JsonSerializer.ReadObject( _Response.GetResponseStream() );
				_ReturnValue.AddRange( _TwitterResults.statuses );
			}

			return _ReturnValue;
		}
开发者ID:freestylecoder,项目名称:TwitterAuthTool,代码行数:27,代码来源:TwitterAuthTool.cs

示例5: OfflineDownload

 static string OfflineDownload(string url, string path)
 {
     string respHTML = Util.HttpPost("https://api.dropboxapi.com/1/save_url/auto/" + path + "?", "url=" + url, token);
     DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(OfflineTask));
     OfflineTask link = (OfflineTask)ser.ReadObject(new MemoryStream(Encoding.ASCII.GetBytes(respHTML)));
     return link.job;
 }
开发者ID:tiancaihb,项目名称:CloudConnect-dev,代码行数:7,代码来源:HelloDropbox.cs

示例6: GetAccountInfo

 static void GetAccountInfo()
 {
     string respHTML = Util.HttpGet("https://api.dropboxapi.com/1/account/info", token);
     DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(Person));
     Person personinfo = (Person)ser.ReadObject(new MemoryStream(Encoding.ASCII.GetBytes(respHTML)));
     Console.WriteLine(personinfo.display_name + " " + personinfo.email + " " + personinfo.quota_info.normal + "/" + personinfo.quota_info.quota);
 }
开发者ID:tiancaihb,项目名称:CloudConnect-dev,代码行数:7,代码来源:HelloDropbox.cs

示例7: GetDownloadLink

 static void GetDownloadLink()
 {
     string respHTML = Util.HttpPost("https://api.dropboxapi.com/1/media/auto/simple.txt", "", token);
     DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(DownloadLink));
     DownloadLink link = (DownloadLink)ser.ReadObject(new MemoryStream(Encoding.ASCII.GetBytes(respHTML)));
     Console.WriteLine(link.url);
 }
开发者ID:tiancaihb,项目名称:CloudConnect-dev,代码行数:7,代码来源:HelloDropbox.cs

示例8: Deserialize

 public object Deserialize(WebFormatterDeserializationContext context, Type type)
 {
     if (context.ContentFormat != WebFormatterDeserializationContext.DeserializationFormat.Xml)
         throw new InvalidDataException("Data must be in xml format.");
     var serializer = new DataContractJsonSerializer(type);
     return serializer.ReadObject(context.XmlReader);
 }
开发者ID:huoxudong125,项目名称:WcfRestContrib,代码行数:7,代码来源:DataContractJson.cs

示例9: MessageProcess

        public void MessageProcess(object objMessage)
        {
            status status = new status();
            Logger logger = new Logger();
            DataContractJsonSerializer json = new DataContractJsonSerializer(status.GetType());

            try
            {
                Message message = objMessage as Message;

                byte[] byteArray = Encoding.UTF8.GetBytes(message.Body.ToString());
                MemoryStream stream = new MemoryStream(byteArray);

                //TODO:  Check for multiple objects.
                status = json.ReadObject(stream) as status;

                Console.WriteLine(message.Body.ToString());

                //TODO: Store the status object
                DataStore.Add(status);
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                logger.append(ex.Message, Logger.LogLevel.ERROR);
            }
        }
开发者ID:swhitley,项目名称:TwitterStreamClient,代码行数:27,代码来源:TwitterStream.cs

示例10: DeserializeOrderBlob

 private PaymentReceipt DeserializeOrderBlob(PaymentReceipt receipt)
 {
     var ser = new DataContractJsonSerializer(typeof (PaymentReceipt));
     var ms = new MemoryStream(Encoding.UTF8.GetBytes(receipt.orderblob));
     var deserializeReceipt = (PaymentReceipt) ser.ReadObject(ms);
     return deserializeReceipt;
 }
开发者ID:robcar,项目名称:getingarna,代码行数:7,代码来源:OrderController.cs

示例11: SimpleInjectionViaStringAsJson

        /// <summary>
        /// This example uses the raw JSON string to create a POST
        /// request for sending one or more SMTP messages through Email-On-Demand.
        /// 
        /// The JSON request generated by this sample code looks like this:
        /// 
        ///{
        ///    "ServerId": "YOUR SERVER ID HERE",
        ///    "ApiKey": "YOUR API KEY HERE",
        ///    "Messages": [{
        ///        "Subject": "Email subject line for raw JSON example.",
        ///        "TextBody": "The text portion of the message.",
        ///        "HtmlBody": "<h1>The html portion of the message</h1><br/>Test",
        ///        "To": [{
        ///            "EmailAddress": "[email protected]",
        ///            "FriendlyName": "Customer Name"
        ///        }],
        ///        "From": {
        ///            "EmailAddress": "[email protected]",
        ///            "FriendlyName": "From Address"
        ///        },
        ///    }]
        ///}
        /// </summary>
        public static void SimpleInjectionViaStringAsJson(
            int serverId, string yourApiKey, string apiUrl)
        {
            // The client object processes requests to the SocketLabs Injection API.
            var client = new RestClient(apiUrl);

            // Construct the string used to generate JSON for the POST request.
            string stringBody =
                "{" +
                    "\"ServerId\":\"" + serverId + "\"," +
                    "\"ApiKey\":\"" + yourApiKey + "\"," +
                    "\"Messages\":[{" +
                        "\"Subject\":\"Email subject line for raw JSON example.\"," +
                        "\"TextBody\":\"The text portion of the message.\"," +
                        "\"HtmlBody\":\"<h1>The html portion of the message</h1><br/>Test\"," +
                        "\"To\":[{" +
                            "\"EmailAddress\":\"[email protected]\"," +
                            "\"FriendlyName\":\"Customer Name\"" +
                        "}]," +
                        "\"From\":{" +
                            "\"EmailAddress\":\"[email protected]\"," +
                            "\"FriendlyName\":\"From Address\"" +
                        "}," +
                    "}]" +
                "}";

            try
            {
                // Generate a new POST request.
                var request = new RestRequest(Method.POST) { RequestFormat = DataFormat.Json };

                // Store the request data in the request object.
                request.AddParameter("application/json; charset=utf-8", stringBody, ParameterType.RequestBody);

                // Make the POST request.
                var result = client.ExecuteAsPost(request, "POST");

                // Store the response result in our custom class.
                using (var stream = new MemoryStream(Encoding.UTF8.GetBytes(result.Content)))
                {
                    var serializer = new DataContractJsonSerializer(typeof (PostResponse));
                    var resp = (PostResponse) serializer.ReadObject(stream);

                    // Display the results.
                    if (resp.ErrorCode.Equals("Success"))
                    {
                        Console.WriteLine("Successful injection!");
                    }
                    else
                    {
                        Console.WriteLine("Failed injection! Returned JSON is: ");
                        Console.WriteLine(result.Content);
                    }
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine("Error, something bad happened: " + ex.Message);
            }
        }
开发者ID:JoeSocketLabs,项目名称:email-on-demand-examples,代码行数:84,代码来源:JsonString.cs

示例12: AsyncPresence

        /// <summary>
        /// Get Presence information per user.
        /// </summary>
        private async void AsyncPresence()
        {
            var client = new HttpClient();

            var uri = new Uri(string.Format(Configurations.PresenceUrl, Configurations.ApiKey, _currentMember.id));
            var response = await client.GetAsync(uri);
            var statusCode = response.StatusCode;
            switch (statusCode)
            {
                // TODO: Error handling for invalid htpp responses.
            }
            response.EnsureSuccessStatusCode();
            var theResponse = await response.Content.ReadAsStringAsync();
            using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(theResponse)))
            {
                var serializer = new DataContractJsonSerializer(typeof(PresenceRoot));
                var presenceObject = serializer.ReadObject(ms) as PresenceRoot;
                // This will allow the application to toggle the presence indicator color.    
                if (presenceObject != null && presenceObject.ok && presenceObject.IsActive())
                {
                    await Windows.ApplicationModel.Core.CoreApplication.MainView.CoreWindow.Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
                    {
                        StatusIndicator.Fill = new SolidColorBrush(Color.FromArgb(255, 127, 153, 71));
                    });
                }
                // TODO: Add more code for bad replies or invalid requests.
            }
        }
开发者ID:firebellys,项目名称:slack-list,代码行数:31,代码来源:ProfilePage.xaml.cs

示例13: HandleResponse

        void HandleResponse(IAsyncResult ar)
        {
            try
            {
                WebResponse response = ((HttpWebRequest)ar.AsyncState).EndGetResponse(ar);


                var serializer = new DataContractJsonSerializer(typeof(respuesta));

                var resp = (respuesta)serializer.ReadObject(response.GetResponseStream());

                Dispatcher.BeginInvoke(() =>
                {

                    this.DataContext = resp;
                    PhoneApplicationService.Current.State["respuesta"] = resp;

                });
            }
            catch (Exception ex)
            {
                Dispatcher.BeginInvoke(() => {
                    MessageBox.Show("Tuvimos problema accediendo al internet (" + uri + "), favor verificar.");
                    NavigationService.GoBack();
                });
                
            }
            
        }
开发者ID:hminaya,项目名称:DevDomSocialAppWP7,代码行数:29,代码来源:MainPage.xaml.cs

示例14: CanRetrieveSimpleResourceDetails

        public void CanRetrieveSimpleResourceDetails()
        {
            using (var host = new InMemoryHost(new SampleApi.Configuration()))
            {
                var request = new InMemoryRequest
                {
                    Uri = new Uri("http://localhost/api-docs/simple"),
                    HttpMethod = "GET",
                    Entity = {ContentType = MediaType.Json}
                };

                request.Entity.Headers["Accept"] = "application/json";

                var response = host.ProcessRequest(request);
                var statusCode = response.StatusCode;
                Assert.AreEqual(200, statusCode);

                Assert.IsTrue(response.Entity.ContentLength>0);

                response.Entity.Stream.Seek(0, SeekOrigin.Begin);

                var serializer = new DataContractJsonSerializer(typeof(ResourceDetails));
                var resourceDetails = (ResourceDetails) serializer.ReadObject(response.Entity.Stream);

                Assert.IsNotNull(resourceDetails);
            }
        }
开发者ID:huoxudong125,项目名称:OpenRastaSwagger,代码行数:27,代码来源:SampleApiTests.cs

示例15: Page_Load

		protected void Page_Load(object sender, EventArgs e) {
			this.RegisterAsyncTask(
				new PageAsyncTask(
					async ct => {
						IAuthorizationState authorization = await client.ProcessUserAuthorizationAsync(new HttpRequestWrapper(Request), ct);
						if (authorization == null) {
							// Kick off authorization request
							var request = await client.PrepareRequestUserAuthorizationAsync(cancellationToken: ct);
							await request.SendAsync();
							this.Context.Response.End();
						} else {
							string token = authorization.AccessToken;
							AzureADClaims claimsAD = client.ParseAccessToken(token);

							// Request to AD needs a {tenantid}/users/{userid}
							var request =
								WebRequest.Create("https://graph.windows.net/" + claimsAD.Tid + "/users/" + claimsAD.Oid + "?api-version=0.9");
							request.Headers = new WebHeaderCollection();
							request.Headers.Add("authorization", token);
							using (var response = request.GetResponse()) {
								using (var responseStream = response.GetResponseStream()) {
									var serializer = new DataContractJsonSerializer(typeof(AzureADGraph));
									AzureADGraph graphData = (AzureADGraph)serializer.ReadObject(responseStream);
									this.nameLabel.Text = HttpUtility.HtmlEncode(graphData.DisplayName);
								}
							}
						}
					}));
		}
开发者ID:Balamir,项目名称:DotNetOpenAuth,代码行数:29,代码来源:AzureAD.aspx.cs


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