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


C# JsonObject.Add方法代码示例

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


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

示例1: AddTest

        public void AddTest()
        {
            string key1 = AnyInstance.AnyString;
            string key2 = AnyInstance.AnyString2;
            JsonValue value1 = AnyInstance.AnyJsonValue1;
            JsonValue value2 = AnyInstance.AnyJsonValue2;

            JsonObject target;

            target = new JsonObject();
            target.Add(new KeyValuePair<string, JsonValue>(key1, value1));
            Assert.Equal(1, target.Count);
            Assert.True(target.ContainsKey(key1));
            Assert.Equal(value1, target[key1]);

            target.Add(key2, value2);
            Assert.Equal(2, target.Count);
            Assert.True(target.ContainsKey(key2));
            Assert.Equal(value2, target[key2]);

            ExceptionHelper.Throws<ArgumentNullException>(delegate { new JsonObject().Add(null, value1); });
            ExceptionHelper.Throws<ArgumentNullException>(delegate { new JsonObject().Add(new KeyValuePair<string, JsonValue>(null, value1)); });

            ExceptionHelper.Throws<ArgumentException>(delegate { new JsonObject().Add(key1, AnyInstance.DefaultJsonValue); });
            ExceptionHelper.Throws<ArgumentException>(delegate { new JsonArray().Add(AnyInstance.DefaultJsonValue); });
        }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:26,代码来源:JsonObjectTest.cs

示例2: AnswerHttp

		//Using ModernHTTPClient
		private async Task<JsonValue> AnswerHttp(string question)
		{
			JsonValue jsonDoc = null;
			const string dataset = "travel";
			var questionJson = new JsonObject();
			questionJson.Add("questionText", question);
			var evidenceRequest = new JsonObject();
			evidenceRequest.Add("items", 1);
			questionJson.Add("evidenceRequest", evidenceRequest);
			var postData = new JsonObject();
			postData.Add("question", questionJson);

			string text = postData.ToString();
			var _nativehandler = new NativeMessageHandler ();

			using (var content = new StringContent(text, Encoding.UTF8, "application/json"))
			using (var client = new HttpClient(_nativehandler))
			{
			
				client.DefaultRequestHeaders.Authorization=new System.Net.Http.Headers.AuthenticationHeaderValue("Basic", 
					Convert.ToBase64String(
						System.Text.ASCIIEncoding.ASCII.GetBytes(
							string.Format("{0}:{1}", username,password))));
				client.DefaultRequestHeaders.Accept.Add (new System.Net.Http.Headers.MediaTypeWithQualityHeaderValue ("application/json"));
				var response = await client.PostAsync(baseURL, content).ConfigureAwait(false);
				if (response.IsSuccessStatusCode)
				{
					var jsonOut = await response.Content.ReadAsStringAsync().ConfigureAwait(false);
					jsonDoc = await Task.Run (() => JsonObject.Parse (jsonOut));
				}
			}

			return jsonDoc;
		}
开发者ID:xhackers,项目名称:IBM-Bluemix-Hack,代码行数:35,代码来源:MainActivity.cs

示例3: ValidJsonObjectRoundTrip

        public void ValidJsonObjectRoundTrip()
        {
            bool oldValue = CreatorSettings.CreateDateTimeWithSubMilliseconds;
            CreatorSettings.CreateDateTimeWithSubMilliseconds = false;
            try
            {
                int seed = 1;
                Log.Info("Seed: {0}", seed);
                Random rndGen = new Random(seed);

                JsonObject sourceJson = new JsonObject(new Dictionary<string, JsonValue>()
                {
                    { "Name", PrimitiveCreator.CreateInstanceOfString(rndGen) },
                    { "Age", PrimitiveCreator.CreateInstanceOfInt32(rndGen) },
                    { "DateTimeOffset", PrimitiveCreator.CreateInstanceOfDateTimeOffset(rndGen) },
                    { "Birthday", PrimitiveCreator.CreateInstanceOfDateTime(rndGen) }
                });
                sourceJson.Add("NewItem1", PrimitiveCreator.CreateInstanceOfString(rndGen));
                sourceJson.Add(new KeyValuePair<string, JsonValue>("NewItem2", PrimitiveCreator.CreateInstanceOfString(rndGen)));

                JsonObject newJson = (JsonObject)JsonValue.Parse(sourceJson.ToString());

                newJson.Remove("NewItem1");
                sourceJson.Remove("NewItem1");

                Assert.False(newJson.ContainsKey("NewItem1"));

                Assert.False(!JsonValueVerifier.Compare(sourceJson, newJson));
            }
            finally
            {
                CreatorSettings.CreateDateTimeWithSubMilliseconds = oldValue;
            }
        }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:34,代码来源:JsonStringRoundTripTests.cs

示例4: ToJsonString

 /// <summary>
 /// JSON 文字列に変換します。
 /// </summary>
 /// <returns>JSON 文字列。</returns>
 public string ToJsonString()
 {
     var obj = new JsonObject(DateTimeOffset.Now);
     obj.Add(TaskMeta.Name, (JsonValue)Name);
     obj.Add(TaskMeta.Done, (JsonValue)Done);
     return obj.ToString();
 }
开发者ID:tnakamura,项目名称:SilverTask,代码行数:11,代码来源:Task.cs

示例5: loginButton_Click

        private void loginButton_Click(object sender, EventArgs e)
        {
            saveSettings();

            HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://cold-planet-7717.herokuapp.com/sessions.json");
            request.Method = "POST";
            request.CookieContainer = new CookieContainer();

            JsonObject sessionObject = new JsonObject();
            JsonObject infoObject = new JsonObject();

            infoObject.Add(new KeyValuePair<string, JsonValue>("email", usernameTextBox.Text));
            infoObject.Add(new KeyValuePair<string, JsonValue>("password", passwordTextBox.Text));
            infoObject.Add(new KeyValuePair<string, JsonValue>("apns", ""));

            sessionObject.Add(new KeyValuePair<string, JsonValue>("session", infoObject));

            byte[] byteArray = Encoding.UTF8.GetBytes(sessionObject.ToString());

            request.ContentType = "application/json";
            request.ContentLength = byteArray.Length;

            Stream dataStream = request.GetRequestStream();
            dataStream.Write(byteArray, 0, byteArray.Length);
            dataStream.Close();

            HttpWebResponse response = (HttpWebResponse)request.GetResponse();

            dataStream = response.GetResponseStream();

            StreamReader reader = new StreamReader(dataStream);

            string responseFromServer = reader.ReadToEnd();

            if (responseFromServer != null)
            {
                JsonObject responseObject = (JsonObject)JsonValue.Parse(responseFromServer);

                Form2 feed = new Form2();

                request.CookieContainer.Add(response.Cookies);

                feed.request = request;
                feed.cookies = request.CookieContainer;
                feed.userID = (string)responseObject["id"];

                feed.Show();

                this.Hide();
            }

            reader.Close();
            dataStream.Close();
            response.Close();
        }
开发者ID:carbamide,项目名称:JukaelaSocialWindows,代码行数:55,代码来源:Form1.cs

示例6: doLogin

		public static async Task < JsonValue > doLogin(String cpf, String password) {
			String url = "http://10.10.15.41:8080/Futebol/rest/login/authenticate";
			HttpWebResponse response = null;


			HttpWebRequest request = (HttpWebRequest) HttpWebRequest.Create(new Uri(url));
			request.ContentType = "application/json";
			request.Method = "POST";


			/* Monta o objeto json */
			using(var streamWriter = new StreamWriter(request.GetRequestStream())) {
				JsonObject json = new JsonObject();

				json.Add("cpf", cpf);
				json.Add("password", password);
				streamWriter.Write(json.ToString());
				streamWriter.Flush();
				streamWriter.Close();
			}

			/* Chama o serviço REST */
			try {
				using(response = await request.GetResponseAsync() as HttpWebResponse) {
					if (response.StatusCode == HttpStatusCode.OK) {
						using(Stream stream = response.GetResponseStream()) {

							JsonValue jsonDoc = await Task.Run(() => JsonObject.Load(stream));

							Console.Out.WriteLine("Response: {0}", jsonDoc.ToString());
							return jsonDoc;
						}


						//Console.Write("Guilherme " + response.StatusCode);
					} else {
						JsonObject jo = new JsonObject();
						jo.Add("sucess", false);
						return JsonValue.Parse(jo.ToString());
					}
				}
			} catch (WebException e) {

				Console.Write("GUILHERME ERROR: ", e);
				JsonValue error = null;
				return error;

			}


		}
开发者ID:guilhermeikeda,项目名称:mobile-xamarin,代码行数:51,代码来源:Login.cs

示例7: FetchAnswer

		public async Task<JsonValue> FetchAnswer(string question)
		{
			
			const string dataset = "travel";
			var questionJson = new JsonObject();
			questionJson.Add("questionText", question);
			var evidenceRequest = new JsonObject();
			evidenceRequest.Add("items", 1);
			questionJson.Add("evidenceRequest", evidenceRequest);
			var postData = new JsonObject();
			postData.Add("question", questionJson);

			string text = postData.ToString();

			HttpWebRequest profileRequest = (HttpWebRequest)WebRequest.Create(baseURL);
			string _auth = string.Format("{0}:{1}", username, password);
			string _enc = Convert.ToBase64String(Encoding.ASCII.GetBytes(_auth));
			string _cred = string.Format("{0} {1}", "Basic", _enc);
			profileRequest.Headers[HttpRequestHeader.Authorization] = _cred;
			profileRequest.Accept = "application/json";
			profileRequest.ContentType = "application/json";
			byte[] bytes = Encoding.UTF8.GetBytes(text);
			profileRequest.Method = "POST";
			profileRequest.ContentLength = bytes.Length;
			using (Stream requeststream = profileRequest.GetRequestStream())
			{
				requeststream.Write(bytes, 0, bytes.Length);
				requeststream.Close();
			}

			// Send the request to the server and wait for the response:
			using (WebResponse response = await profileRequest.GetResponseAsync ())
			{
				// Get a stream representation of the HTTP web response:
				using (Stream stream = response.GetResponseStream ())
				{
					// Use this stream to build a JSON document object:
					JsonValue jsonDoc = await Task.Run (() => JsonObject.Load (stream));
					Console.Out.WriteLine("Response: {0}", jsonDoc.ToString ());

					// Return the JSON document:
					return jsonDoc;
				}
			}
		}
开发者ID:xhackers,项目名称:IBM-Bluemix-Hack,代码行数:45,代码来源:QuestionAndAnswers.cs

示例8: CreateJsonContent

 public static HttpContent CreateJsonContent(params KeyValuePair<string, string>[] items)
 {
     var jsonObject = new JsonObject();
     foreach (KeyValuePair<string, string> kv in items)
     {
         jsonObject.Add(kv.Key, kv.Value);
     }
     return new ObjectContent(typeof(JsonObject), jsonObject, "application/json");
 }
开发者ID:loudej,项目名称:kudu,代码行数:9,代码来源:HttpClientHelper.cs

示例9: Save

		/// <summary>
		/// 設定を保存します
		/// </summary>
		public async Task Save()
		{
			await Task.Run(() =>
			{
				// Serialize
				var json = new JsonObject();
				JsonPrimitive element;

				JsonPrimitive.TryCreate(Account.BaseUrl, out element);
				json.Add("BaseUrl", element);

				JsonPrimitive.TryCreate(Account.UserKey, out element);
				json.Add("UserKey", element);

				JsonPrimitive.TryCreate(PostTextFormat, out element);
				json.Add("PostTextFormat", element);

				JsonPrimitive.TryCreate((int)TargetPlayer, out element);
				json.Add("TargetPlayer", element);

				JsonPrimitive.TryCreate(IsAutoPost, out element);
				json.Add("IsAutoPost", element);

				JsonPrimitive.TryCreate(AutoPostInterval, out element);
				json.Add("AutoPostInterval", element);

				// Save
				using (var sw = new System.IO.StreamWriter("setting.json"))
				{
					json.Save(sw);
				}
			});
		}
开发者ID:marihachi,项目名称:MisskeyNowPlaying,代码行数:36,代码来源:SettingStorage.cs

示例10: userRegister

        public static bool userRegister(User user)
        {
            String url = "http://10.10.15.41:8080/Futebol/rest/user/register";

            HttpWebRequest request = (HttpWebRequest)HttpWebRequest.Create (new Uri (url));
            request.ContentType = "application/json";
            request.Method = "POST";

            /* Monta o objeto json */
            using(var streamWriter = new StreamWriter(request.GetRequestStream())) {
                JsonObject json = new JsonObject();

                json.Add("firstName", user.firstName);
                json.Add("lastName", user.lastName);
                json.Add("cpf", user.cpf);
                json.Add("password", user.password);

                streamWriter.Write(json.ToString());
                streamWriter.Flush();
                streamWriter.Close();
            }

            /* Chama o serviço REST */
            try {
                HttpWebResponse response = (HttpWebResponse)request.GetResponse();
                if(response.StatusCode.Equals(HttpStatusCode.OK)){
                    return true;
                }else{
                    return false;
                }
            } catch (WebException e) {

                Console.Write("GUILHERME ERROR: ", e);
                JsonValue error = null;
                return error;

            }
        }
开发者ID:guilhermeikeda,项目名称:mobile-xamarin,代码行数:38,代码来源:UserRegister.cs

示例11: buildJson

        private string buildJson(string playerId, int score, GameMode mode, GameDifficulty difficulty, DateTime date, Dictionary<int, bool> answers)
        {
            //			{
            //			“player”:”Varyon”,
            //			“score”:10000,
            //			“difficulty”:0,
            //			“mode”:0,
            //			“date”:”2012-03-07 23:15:00”,
            //			“answers”: [
            //				           {“id” : 002, “result” : false},
            //				           {“id” : 003, “result” : true},
            //				            ]
            //			}

            JsonObject json = new JsonObject ();

            json.Add ("player", new JsonPrimitive (playerId));
            json.Add ("score", new JsonPrimitive (score));
            json.Add ("mode", new JsonPrimitive ((int)mode));
            json.Add ("difficulty", new JsonPrimitive ((int)difficulty));
            json.Add ("date", new JsonPrimitive (date.ToString ("yyyy-MM-dd hh:mm:ss")));

            List<JsonValue> answersItemsJson = new List<JsonValue> ();
            foreach (var gameId in answers.Keys) {

                JsonObject o = new JsonObject();
                o.Add("id", new JsonPrimitive(gameId));
                o.Add("result", new JsonPrimitive(answers[gameId]));

                answersItemsJson.Add (o);
            }

            JsonArray answersJson = new JsonArray (answersItemsJson);
            json.Add ("answers", answersJson);

            return json.ToString ();
        }
开发者ID:valryon,项目名称:super-koikoukesse,代码行数:37,代码来源:ServiceStats.cs

示例12: CreateJsonObject

        static JsonObject CreateJsonObject(Random rndGen, int depth)
        {
            const string keyChars = "abcdefghijklmnopqrstuvwxyz0123456789";
            int size = rndGen.Next(CreatorSettings.MaxArrayLength);
            if (CreatorSettings.NullValueProbability == 0 && size == 0)
            {
                size++;
            }

            JsonObject result = new JsonObject();
            for (int i = 0; i < size; i++)
            {
                string key;
                do
                {
                    key = PrimitiveCreator.CreateInstanceOfString(rndGen, 10, keyChars);
                } while (result.ContainsKey(key));

                result.Add(key, CreateJsonValue(rndGen, depth + 1));
            }

            return result;
        }
开发者ID:nuxleus,项目名称:WCFWeb,代码行数:23,代码来源:JsonValueCreatorSurrogate.cs

示例13: ToJson

        internal JsonObject ToJson()
        {
            var user_info = new JsonObject();
            foreach (var kvp in UserInfo)
            {
                JsonValue value = null;
                if (kvp.Value is string)
                {
                    value = (string)kvp.Value;
                }
                else if (kvp.Value is bool)
                {
                    value = (bool)kvp.Value;
                }
                else
                {
                    System.Diagnostics.Debug.Fail($"Unsupported type in JSON conversion '{kvp.Value?.GetType()}'");
                }

                user_info.Add(kvp.Key, value);
            }

            return new JsonObject
            {
                ["data"] = Token,
                ["provider"] = IdentityProvider,
                ["user_info"] = user_info
            };
        }
开发者ID:realm,项目名称:realm-dotnet,代码行数:29,代码来源:Credentials.cs

示例14: CountTest

        public void CountTest()
        {
            string key1 = AnyInstance.AnyString;
            string key2 = AnyInstance.AnyString2;
            JsonValue value1 = AnyInstance.AnyJsonValue1;
            JsonValue value2 = AnyInstance.AnyJsonValue2;

            JsonObject target = new JsonObject();
            Assert.Equal(0, target.Count);
            target.Add(key1, value1);
            Assert.Equal(1, target.Count);
            target.Add(key2, value2);
            Assert.Equal(2, target.Count);
            target.Remove(key2);
            Assert.Equal(1, target.Count);
        }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:16,代码来源:JsonObjectTest.cs

示例15: ContainsKVPTest

 public void ContainsKVPTest()
 {
     JsonObject target = new JsonObject();
     KeyValuePair<string, JsonValue> item = new KeyValuePair<string, JsonValue>(AnyInstance.AnyString, AnyInstance.AnyJsonValue1);
     KeyValuePair<string, JsonValue> item2 = new KeyValuePair<string, JsonValue>(AnyInstance.AnyString2, AnyInstance.AnyJsonValue2);
     target.Add(item);
     Assert.True(((ICollection<KeyValuePair<string, JsonValue>>)target).Contains(item));
     Assert.False(((ICollection<KeyValuePair<string, JsonValue>>)target).Contains(item2));
 }
开发者ID:haoduotnt,项目名称:aspnetwebstack,代码行数:9,代码来源:JsonObjectTest.cs


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