本文整理汇总了C#中System.Runtime.Serialization.Json.DataContractJsonSerializer类的典型用法代码示例。如果您正苦于以下问题:C# DataContractJsonSerializer类的具体用法?C# DataContractJsonSerializer怎么用?C# DataContractJsonSerializer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
DataContractJsonSerializer类属于System.Runtime.Serialization.Json命名空间,在下文中一共展示了DataContractJsonSerializer类的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: ResponseCallback
private void ResponseCallback(IAsyncResult result)
{
var state = (List<object>) result.AsyncState;
var googleRequest = (GooglePlaceSearchRequest) state[1];
if (result.IsCompleted)
{
try
{
var request = (HttpWebRequest)state[0];
var response = (HttpWebResponse)request.EndGetResponse(result);
var responseStream = response.GetResponseStream();
var serializer = new DataContractJsonSerializer(typeof(GooglePlaceSearchResponse));
var googleSearchResponse = (GooglePlaceSearchResponse)serializer.ReadObject(responseStream);
if (googleSearchResponse.Status == GoogleMapsSearchStatus.OK)
SearchForPlacesAsyncCompleted(googleSearchResponse, googleRequest);
else if (googleSearchResponse.Status == GoogleMapsSearchStatus.ZERO_RESULTS)
SearchForPlacesAsyncNotFound(googleSearchResponse, googleRequest);
} catch(Exception e)
{
if (SearchForPlacesAsyncFailed!= null)
SearchForPlacesAsyncFailed(e.Message, e);
}
} else
{
if (SearchForPlacesAsyncFailed != null)
SearchForPlacesAsyncFailed("For some reason request is not completed", null);
}
}
示例3: 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);
}
}
}
}));
}
示例4: AutenticateWNS
private void AutenticateWNS()
{
try
{
// get an access token
var urlEncodedSid = HttpUtility.UrlEncode(String.Format("{0}", this.Sid));
var urlEncodedSecret = HttpUtility.UrlEncode(this.Secret);
var uri =
String.Format("grant_type=client_credentials&client_id={0}&client_secret={1}&scope=notify.windows.com",
urlEncodedSid,
urlEncodedSecret);
var client = new WebClient();
client.Headers.Add("Content-Type", "application/x-www-form-urlencoded");
string response = client.UploadString("https://login.live.com/accesstoken.srf", uri);
// parse the response in JSON format
OAuthToken token;
using (var ms = new MemoryStream(Encoding.Unicode.GetBytes(response)))
{
var ser = new DataContractJsonSerializer(typeof(OAuthToken));
token = (OAuthToken)ser.ReadObject(ms);
}
this.accessToken = token.AccessToken;
}
catch (Exception ex)
{
//lblResult.Text = ex.Message;
//lblResult.ForeColor = System.Drawing.Color.Red;
throw ex;
}
}
示例5: 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);
}
示例6: 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);
}
}
示例7: All
//TODO: now it is assuming that the "generated" type name is the same, can we assume that?
public IEnumerable<string> All(string typeName)
{
IProvider provider = ProviderConfiguration.GetProvider(typeName);
Type type = provider.Type;
IEnumerable objects = provider.All();
List<string> result = new List<string>();
foreach (var obj in objects)
{
using (MemoryStream stream = new MemoryStream())
{
DataContractJsonSerializer serializer = new DataContractJsonSerializer(type);
serializer.WriteObject(stream, obj);
stream.Position = 0;
using (StreamReader reader = new StreamReader(stream))
{
result.Add(reader.ReadToEnd());
}
}
}
return result;
//return
// "{ \"<Id>k__BackingField\": \"patients/1\", \"<Name>k__BackingField\": \"Margol Foo\",\"Name\": \"Margol Foo\"}";
}
示例8: ToJson
public static string ToJson(this object obj)
{
if (obj == null)
{
return "null";
}
DataContractJsonSerializer ser = new DataContractJsonSerializer(obj.GetType());
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, obj);
ms.Position = 0;
string json = String.Empty;
using (StreamReader sr = new StreamReader(ms))
{
json = sr.ReadToEnd();
}
//ms.Close();
return json;
}
示例9: handleReply
public void handleReply(string json)
{
if (json == null)
{
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
progressBar1.IsIndeterminate = false;
MessageBox.Show("Unable to communicate with server.");
});
return;
}
DataContractJsonSerializer dcjs = new DataContractJsonSerializer(typeof(StudentResponse));
student = dcjs.ReadObject(new MemoryStream(Encoding.Unicode.GetBytes(json))) as StudentResponse;
Deployment.Current.Dispatcher.BeginInvoke(() =>
{
this.tStudentName.Text = student.nome;
StudentProfileModel.Items[0].LineTwo = student.codigo;
StudentProfileModel.Items[1].LineTwo = student.email;
StudentProfileModel.Items[2].LineTwo = student.email_alternativo;
StudentProfileModel.Items[3].LineTwo = student.curso_nome;
StudentProfileModel.Items[4].LineTwo = student.estado;
StudentProfileModel.Items[5].LineTwo = student.ano_curricular.ToString();
TiltEffect.SetIsTiltEnabled(lbItems.ItemContainerGenerator.ContainerFromIndex(1), true);
TiltEffect.SetIsTiltEnabled(lbItems.ItemContainerGenerator.ContainerFromIndex(2), true);
if (student.email_alternativo == null)
StudentProfileModel.Items.RemoveAt(2);
this.lbItems.SelectionChanged += new SelectionChangedEventHandler(sendEmailHandler);
progressBar1.IsIndeterminate = false;
});
}
示例10: OnPreRender
protected override void OnPreRender(EventArgs e)
{
if (!this.ReadOnlyMode && !UseBrowseTemplate)
{
string jsonData;
using (var s = new MemoryStream())
{
var workData = ContentType.GetContentTypes()
.Select(n => new ContentTypeItem {value = n.Name, label = n.DisplayName, path = n.Path, icon = n.Icon})
.OrderBy(n => n.label);
var serializer = new DataContractJsonSerializer(typeof (ContentTypeItem[]));
serializer.WriteObject(s, workData.ToArray());
s.Flush();
s.Position = 0;
using (var sr = new StreamReader(s))
{
jsonData = sr.ReadToEnd();
}
}
// init control happens in prerender to handle postbacks (eg. pressing 'inherit from ctd' button)
var contentTypes = _contentTypes ?? GetContentTypesFromControl();
InitControl(contentTypes);
var inherit = contentTypes == null || contentTypes.Count() == 0 ? 0 : 1;
UITools.RegisterStartupScript("initdropboxautocomplete", string.Format("SN.ACT.init({0},{1})", jsonData, inherit), this.Page);
}
base.OnPreRender(e);
}
示例11: Page_Load
protected void Page_Load(object sender, EventArgs e)
{
Status.RecordHit();
String numFacesString = Request.QueryString["numFaces"];
int numFaces = numFacesString == null ? 20 : int.Parse(numFacesString);
if (numFaces > 100) numFaces = 100;
var faces = FacesLite.GetRandomFaces(numFaces).ToArray();
Message mess = new Message();
mess.FaceImages = new List<FaceImage>();
for (int i = 0; i < faces.Count(); i++)
{
FaceImage fi = new FaceImage()
{
ukey = faces[i].Item1,
path = faces[i].Item2
};
mess.FaceImages.Add(fi);
}
DataContractJsonSerializer ser = new DataContractJsonSerializer(typeof(FaceImage[]));
MemoryStream ms = new MemoryStream();
ser.WriteObject(ms, mess.FaceImages.ToArray());
string json = Encoding.UTF8.GetString(ms.ToArray());
ms.Close();
Response.Clear();
Response.ContentType = "application/json; charset=utf-8";
Response.Write(json);
Response.End();
}
示例12: MakeRequest
public static GeocodeResponse MakeRequest(string addressNumber, string streetName, string cityName, string countryName)
{
string requestUrl = CreateGeocodeRequest(addressNumber, streetName, cityName, countryName);
try
{
HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
if (response.StatusCode != HttpStatusCode.OK)
throw new Exception(String.Format(
"Server error (HTTP {0}: {1}).",
response.StatusCode,
response.StatusDescription));
DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(GeocodeResponse));
object objResponse = jsonSerializer.ReadObject(response.GetResponseStream());
GeocodeResponse jsonResponse
= objResponse as GeocodeResponse;
return jsonResponse;
}
}
catch (Exception e)
{
Console.WriteLine(e.Message);
return null;
}
}
示例13: LoadSettingsAsync
/// <summary>
/// Загрузка из локального хранилища настроек в формате JSON
/// </summary>
public async void LoadSettingsAsync()
{
StorageFile settingsFile = null;
bool isExists = true;
try
{
settingsFile = await StorageFile.GetFileFromPathAsync(Constants.SettingsFile);
}
catch (FileNotFoundException)
{
isExists = false;
}
if (!isExists)
{
Settings = new SettingsVariables();
}
else
{
using (var fileStream = await settingsFile.OpenStreamForReadAsync())
{
MemoryStream memoryStream = new MemoryStream();
await fileStream.CopyToAsync(memoryStream);
memoryStream.Position = 0;
DataContractJsonSerializer serializer = new DataContractJsonSerializer(typeof(SettingsVariables));
Settings = (SettingsVariables)serializer.ReadObject(memoryStream);
}
}
}
示例14: 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();
});
}
}
示例15: 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.
}
}