本文整理汇总了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();
}
}
示例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;
}
示例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");
}
示例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;
}
示例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;
}
示例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);
}
示例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);
}
示例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);
}
示例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);
}
}
示例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;
}
示例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);
}
}
示例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.
}
}
示例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();
});
}
}
示例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);
}
}
示例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);
}
}
}
}));
}