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


C# JsonObject.Stringify方法代码示例

本文整理汇总了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();
 }
开发者ID:forehalo,项目名称:UWP-dev,代码行数:28,代码来源:MainPage.xaml.cs

示例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());
		}
开发者ID:romgerman,项目名称:DiscordUWP8,代码行数:33,代码来源:Client.cs

示例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);
            }
        }
开发者ID:jimgrant,项目名称:ProgrammingWindowsStoreApps,代码行数:28,代码来源:ServiceProxy.cs

示例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);
            }
        }
开发者ID:jimgrant,项目名称:ProgrammingWindowsStoreApps,代码行数:56,代码来源:ServiceProxy.cs

示例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;
        }
开发者ID:trilok567,项目名称:Windows-Phone,代码行数:10,代码来源:MainPage.xaml.cs

示例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()));
        }
开发者ID:Rameshcyadav,项目名称:Thinktecture.IdentityModel.45,代码行数:11,代码来源:TokenVault.cs

示例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()));
        }
开发者ID:Griimm,项目名称:Thinktecture.AuthorizationServer,代码行数:13,代码来源:TokenVault.cs

示例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();
 }
开发者ID:Iamnvincible,项目名称:csharppractice,代码行数:13,代码来源:Data.cs

示例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);
        }
开发者ID:cosullivan,项目名称:JsonLite,代码行数:15,代码来源:JsonStringifyFacts.cs

示例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
    }
开发者ID:WimVergouwe,项目名称:ravendb,代码行数:36,代码来源:JsonNetVsWindowsDataJsonTests.cs

示例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();
        }
开发者ID:fqncom,项目名称:tomcraporigami,代码行数:33,代码来源:MainPage.xaml.cs

示例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());
 }
开发者ID:999eagle,项目名称:StartMenuTiles,代码行数:11,代码来源:SteamGameListPageViewModels.cs

示例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;
            });
        }
开发者ID:csff,项目名称:azure-mobile-services,代码行数:84,代码来源:ZumoLoginTests.cs

示例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);
            }
        }
开发者ID:DmitrySigaev,项目名称:Connect-SDK-Windows,代码行数:39,代码来源:WebOstvServiceSocketClient.cs

示例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();
        }
开发者ID:kiewic,项目名称:Questions,代码行数:59,代码来源:SettingsManager.cs


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