本文整理汇总了C#中JsonObject.Stringify方法的典型用法代码示例。如果您正苦于以下问题:C# JsonObject.Stringify方法的具体用法?C# JsonObject.Stringify怎么用?C# JsonObject.Stringify使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类JsonObject
的用法示例。
在下文中一共展示了JsonObject.Stringify方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: OnClick
private async void OnClick(object sender, RoutedEventArgs e)
{
Button btn = sender as Button;
MessageDialog msgBox = new MessageDialog("请输入姓名、城市和年龄。");
if(txtName.Text == "" || txtCity.Text == "" || txtAge.Text == "")
{
await msgBox.ShowAsync();
return;
}
btn.IsEnabled = false;
// 获取文档库目录
StorageFolder doclib = KnownFolders.DocumentsLibrary;
// 将输入的内容转化为 json 对象
JsonObject json = new JsonObject();
json.Add("name", JsonValue.CreateStringValue(txtName.Text));
json.Add("city", JsonValue.CreateStringValue(txtCity.Text));
json.Add("age", JsonValue.CreateNumberValue(Convert.ToDouble(txtAge.Text)));
// 提取出 json 字符串
string jsonStr = json.Stringify();
// 在文档库中创建新文件
string fileName = DateTime.Now.ToString("yyyy-M-d-HHmmss") + ".mydoc";
StorageFile newFile = await doclib.CreateFileAsync(fileName, CreationCollisionOption.ReplaceExisting);
// 将 json 字符串写入文件
await FileIO.WriteTextAsync(newFile, jsonStr);
btn.IsEnabled = true;
msgBox.Content = "保存成功";
await msgBox.ShowAsync();
}
示例2: Connect
public async Task Connect()
{
if (!_isLoggedIn)
throw new DiscordException(ExceptionList.NotLoggedIn);
_socket = new MessageWebSocket();
_writer = new DataWriter(_socket.OutputStream) { UnicodeEncoding = UnicodeEncoding.Utf8 };
_socket.Control.MessageType = SocketMessageType.Utf8;
_socket.MessageReceived += socket_MessageReceived;
string gatewayUrl = await GetGateway();
await _socket.ConnectAsync(new Uri(gatewayUrl));
JsonObject request = new JsonObject
{
{ "op", JsonValue.CreateNumberValue(2) },
{ "d", new JsonObject
{
{ "token", JsonValue.CreateStringValue(_token) },
{ "v", JsonValue.CreateNumberValue(3) },
{ "properties", new JsonObject
{
{ "$os", JsonValue.CreateStringValue("Windows") }
}},
{ "large_threshold", JsonValue.CreateNumberValue(0) }
}
}
};
await WriteToSocket(request.Stringify());
}
示例3: ExecuteAsync
public async Task<ServiceExecuteResult> ExecuteAsync(JsonObject input)
{
// set the api key...
ConfigureInputArgs(input);
// package it us as json...
var json = input.Stringify();
var content = new StringContent(json);
// client...
var client = new HttpClient();
var response = await client.PostAsync(this.Url, content);
// load it up...
var outputJson = await response.Content.ReadAsStringAsync();
JsonObject output = JsonObject.Parse(outputJson);
// did the server return an error?
bool isOk = output.GetNamedBoolean("isOk");
if (isOk)
return new ServiceExecuteResult(output);
else
{
// we have an error returned from the server, so return that...
string error = output.GetNamedString("error");
return new ServiceExecuteResult(output, error);
}
}
示例4: Execute
public async Task<ServiceExecuteResult> Execute(JsonObject input)
{
// set the api key...
ConfigureInputArgs(input);
// create a request...
HttpWebRequest request = HttpWebRequest.CreateHttp(this.Url);
request.Method = "POST";
// make a request for a stream to post the data up...
using (var stream = await request.GetRequestStreamAsync())
{
// get the data to send...
string outboundJson = input.Stringify();
byte[] bs = Encoding.UTF8.GetBytes(outboundJson);
// send it...
stream.Write(bs, 0, bs.Length);
}
// now, the response...
var response = await request.GetResponseAsync();
// unpack...
string inboundJson = null;
using (Stream stream = response.GetResponseStream())
{
// unpack the json...
StreamReader reader = new StreamReader(stream);
inboundJson = reader.ReadToEnd();
}
// load it up...
JsonObject output = JsonObject.Parse(inboundJson);
// did the server return an error?
bool isOk = output.GetNamedBoolean("isOk");
if (isOk)
return new ServiceExecuteResult(output);
else
{
// we have an error returned from the server, so return that...
string error = output.GetNamedString("error");
// do we have more?
const string extendedKey = "generalFailure";
if (output.ContainsKey(extendedKey))
{
string extended = output.GetNamedString(extendedKey);
error = string.Format("{0} -> {1}", error, extended);
}
// return...
return new ServiceExecuteResult(output, error);
}
}
示例5: btnExecuta_Click
private void btnExecuta_Click(object sender, RoutedEventArgs e)
{
JsonObject jsonObject = new JsonObject();
jsonObject["Largura"] = JsonValue.CreateNumberValue(800);
jsonObject["Altura"] = JsonValue.CreateNumberValue(600);
jsonObject["Titulo"] = JsonValue.CreateStringValue("Meu Titulo");
string jsonString = jsonObject.Stringify();
lblResultado.Text = jsonString;
}
示例6: StoreToken
public static void StoreToken(string identifier, TokenResponse response)
{
var json = new JsonObject();
json["access_token"] = JsonValue.CreateStringValue(response.AccessToken);
json["expires_in"] = JsonValue.CreateNumberValue(response.ExpiresIn);
json["token_type"] = JsonValue.CreateStringValue(response.TokenType);
var vault = new PasswordVault();
vault.Add(new PasswordCredential(identifier, "token", json.Stringify()));
}
示例7: StoreToken
public static void StoreToken(string identifier, string accessToken, long ExpiresIn, string tokenType)
{
var json = new JsonObject();
var expiresAt = DateTime.UtcNow.ToEpochTime() + ExpiresIn;
json["access_token"] = JsonValue.CreateStringValue(accessToken);
json["expires_in"] = JsonValue.CreateNumberValue(expiresAt);
json["token_type"] = JsonValue.CreateStringValue(tokenType);
var vault = new PasswordVault();
vault.Add(new PasswordCredential(identifier, "token", json.Stringify()));
}
示例8: GetJson
public string GetJson()
{
JsonArray jsonarray = new JsonArray();
foreach (var school in Education)
{
jsonarray.Add(school.ToJsonObject());
}
JsonObject jsonobject = new JsonObject();
jsonobject["age"] = JsonValue.CreateStringValue(Age.ToString());
jsonobject["name"] = JsonValue.CreateStringValue(Name);
jsonobject["education"] = jsonarray;
return jsonobject.Stringify();
}
示例9: CanParseString
public void CanParseString()
{
// arrange
var value1 = new JsonObject(
new JsonMember("a", new JsonNumber(1)),
new JsonMember("b", new JsonNumber(2)),
new JsonMember("c", new JsonString("\"Hello World\"")));
// act
var value2 = Json.CreateAst(value1.Stringify());
// assert
Assert.IsType<JsonObject>(value2);
Assert.Equal(3, ((JsonObject)value2).Members.Count);
}
示例10: CreatingJson
public void CreatingJson()
{
#if NETFX_CORE
#region CreatingJSON
// Windows.Data.Json
// -----------------
JsonObject jsonObject = new JsonObject
{
{"CPU", JsonValue.CreateStringValue("Intel")},
{
"Drives", new JsonArray
{
JsonValue.CreateStringValue("DVD read/writer"),
JsonValue.CreateStringValue("500 gigabyte hard drive")
}
}
};
string json1 = jsonObject.Stringify();
// LINQ to JSON
// ------------
JObject jObject = new JObject
{
{"CPU", "Intel"},
{
"Drives", new JArray
{
"DVD read/writer",
"500 gigabyte hard drive"
}
}
};
string json2 = jObject.ToString();
#endregion
#endif
}
示例11: GetJson
public static string GetJson(this object obj)
{
var typeInfo = obj.GetType().GetTypeInfo();
var props = typeInfo.DeclaredProperties;
JsonObject jo = new JsonObject();
foreach (var item in props)
{
var propTypeStr = item.PropertyType.ToString();//获取属性类型字符串,进行switch
var propName = item.Name;//获取属性名称
IJsonValue jsonValue = null;//精简代码。简单工厂
switch (propTypeStr)
{
case "System.String":
jsonValue = JsonValue.CreateStringValue(item.GetValue(obj).ToString());
break;
case "System.Double":
jsonValue = JsonValue.CreateNumberValue((double)item.GetValue(obj));
break;
case "System.Int32":
jsonValue = JsonValue.CreateNumberValue((int)item.GetValue(obj));
break;
case "System.Boolean":
jsonValue = JsonValue.CreateBooleanValue((bool)item.GetValue(obj));
break;
default:
break;
}
jo.SetNamedValue(propName, jsonValue);
}
return jo.Stringify();
}
示例12: ExecuteNav
private void ExecuteNav()
{
// data is passed as json
var ja = new JsonObject();
ja.Add("header", JsonValue.CreateStringValue("Steam"));
ja.Add("tile_title", JsonValue.CreateStringValue(m_gameName));
ja.Add("image_wide_url", JsonValue.CreateStringValue(m_imageSource));
ja.Add("action", JsonValue.CreateStringValue("steam://run/" + m_appId));
ja.Add("id", JsonValue.CreateStringValue("Steam\\" + m_appId));
(App.Current as App).NavigationService.Navigate(typeof(CreateTilePage), ja.Stringify());
}
示例13: CreateCRUDTest
private static ZumoTest CreateCRUDTest(string tableName, string providerName, TablePermission tableType, bool userIsAuthenticated)
{
string testName = string.Format(CultureInfo.InvariantCulture, "CRUD, {0}, table with {1} permissions",
userIsAuthenticated ? "unauthenticated" : ("auth by " + providerName), tableType);
return new ZumoTest(testName, async delegate(ZumoTest test)
{
var client = ZumoTestGlobals.Instance.Client;
var table = client.GetTable(tableName);
var crudShouldWork = tableType == TablePermission.Public ||
tableType == TablePermission.Application ||
(tableType == TablePermission.User && userIsAuthenticated);
var item = new JsonObject();
item.Add("Name", JsonValue.CreateStringValue("John Doe"));
int id = 1;
MobileServiceInvalidOperationException ex = null;
try
{
await table.InsertAsync(item);
test.AddLog("Inserted item: {0}", item.Stringify());
id = (int)item["id"].GetNumber();
}
catch (MobileServiceInvalidOperationException e)
{
item["id"] = JsonValue.CreateNumberValue(1); // used in other requests
ex = e;
}
if (!ValidateExpectedError(test, ex, crudShouldWork))
{
return false;
}
ex = null;
try
{
item["Name"] = JsonValue.CreateStringValue("Jane Roe");
await table.UpdateAsync(item);
test.AddLog("Updated item: {0}", item.Stringify());
}
catch (MobileServiceInvalidOperationException e)
{
ex = e;
}
if (!ValidateExpectedError(test, ex, crudShouldWork))
{
return false;
}
ex = null;
try
{
var item2 = await table.LookupAsync(id);
test.AddLog("Retrieved item: {0}", item2.Stringify());
}
catch (MobileServiceInvalidOperationException e)
{
ex = e;
}
if (!ValidateExpectedError(test, ex, crudShouldWork))
{
return false;
}
ex = null;
try
{
await table.DeleteAsync(item);
test.AddLog("Deleted item: {0}", item.Stringify());
}
catch (MobileServiceInvalidOperationException e)
{
ex = e;
}
if (!ValidateExpectedError(test, ex, crudShouldWork))
{
return false;
}
return true;
});
}
示例14: SendMessage
public void SendMessage(JsonObject packet, JsonObject payload)
{
try
{
if (payload != null)
{
packet.Add("payload", payload);
}
}
// ReSharper disable once EmptyGeneralCatchClause
catch
{
}
if (IsConnected())
{
var message = packet.Stringify();
Logger.Current.AddMessage("webOS Socket [OUT]: " + message);
try
{
messageWebSocket.Control.MessageType = SocketMessageType.Utf8;
messageWebSocket.OutputStream.FlushAsync().GetResults();
if (dr == null)
dr = new DataWriter(messageWebSocket.OutputStream);
dr.WriteString(message);
dr.StoreAsync();
}
// ReSharper disable once EmptyGeneralCatchClause
catch
{
HandleConnectionLost(false, null);
}
}
else
{
HandleConnectionLost(false, null);
}
}
示例15: InitializeOrValidateSettings
private static void InitializeOrValidateSettings()
{
if (!roamingValues.ContainsKey("UserId"))
{
// Generate a random user id.
roamingValues["UserId"] = Guid.NewGuid().ToString();
}
// Roaming websites.
roamingWebsites = null;
if (roamingValues.ContainsKey(WebsitesKey))
{
string jsonString = roamingValues[WebsitesKey].ToString();
if (!JsonObject.TryParse(jsonString, out roamingWebsites))
{
roamingWebsites = null;
}
}
if (roamingWebsites == null)
{
roamingWebsites = new JsonObject();
roamingValues[WebsitesKey] = roamingWebsites.Stringify();
}
if (roamingWebsites == null)
{
// This should not be null.
Debugger.Break();
}
// Local websites.
localWebsites = null;
if (localValues.ContainsKey(WebsitesKey))
{
string jsonString = localValues[WebsitesKey].ToString();
Debug.WriteLine("Loading: {0}", jsonString);
if (!JsonObject.TryParse(jsonString, out localWebsites))
{
localWebsites = null;
}
}
if (localWebsites == null)
{
localWebsites = new JsonObject();
localValues[WebsitesKey] = localWebsites.Stringify();
}
if (localWebsites == null)
{
// This should not be null.
Debugger.Break();
}
SyncWebsites();
}