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


C# JsonObject.ToString方法代码示例

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


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

示例1: 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

示例2: PostEntry

 public void PostEntry()
 {
     var json = new JsonObject();
     json["command"] = "entry";
     var send = "data=" + json.ToString();
     network.SendPostRequest(send);
 }
开发者ID:Sweetwater,项目名称:NetworkGame,代码行数:7,代码来源:NetworkController.cs

示例3: 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

示例4: Call

        protected JsonObject Call(string subpath, string method = "GET",  string contentType = "application/text",
            string data = "")
        {
            string uri;

            uri = String.Format("https://{0}{1}", _options["api_base"],
                                    GetPath(subpath));

            if(_sessionId != null && _sessionId != "")
            {
                uri = String.Format("{0}{1}", uri, String.Format("&hs={0}", _sessionId));
            }

            Debug.WriteLine(uri);
            var returnVal = UserWebClient.UploadString(uri, method: method, contentType: contentType, data: data);

            if (returnVal != null)
            {
                if (returnVal.Length > 0)
                {
                    JsonObject o = new JsonObject(JsonValue.Parse(returnVal));
                    if (SuccessfulCall(o))
                    {
                        return o;
                    }
                    else
                    {
                        var response = JsonConvert.DeserializeObject<Helpers.APIResponse>(o.ToString());
                        throw new Exception(String.Format("Unsuccessful call to web api. {0}", response.result.code), new Exception(String.Format("{0}", response.result.description)));
                    }
                }
            }

            return new JsonObject();
        }
开发者ID:cal5fishbowl,项目名称:ISLSharp,代码行数:35,代码来源:BaseClass.cs

示例5: 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

示例6: GetJSONValue

 private string GetJSONValue(Person person)
 {
     dynamic json = new JsonObject();
     json.Id = person.Id;
     json.Balance = person.Balance;
     json.DomainName = person.DomainName;
     return json.ToString();
 }
开发者ID:duda92,项目名称:DinnerAccounting,代码行数:8,代码来源:PeopleController.cs

示例7: JsonObjectOrder

		public void JsonObjectOrder () {
			var obj = new JsonObject ();
			obj["a"] = 1;
			obj["c"] = 3;
			obj["b"] = 2;
			var str = obj.ToString ();
			Assert.AreEqual (str, "{\"a\": 1, \"b\": 2, \"c\": 3}");
		}
开发者ID:ItsVeryWindy,项目名称:mono,代码行数:8,代码来源:JsonValueTest.cs

示例8: StartPolling

 public void StartPolling()
 {
     var data = new JsonObject();
     data["command"] = "polling";
     data["matchKeyName"] = game.Match.KeyName;
     var pollingData = "data=" + data.ToString();
     network.StartPolling(pollingData);
 }
开发者ID:Sweetwater,项目名称:NetworkGame,代码行数:8,代码来源:NetworkController.cs

示例9: PostClickArea

 public void PostClickArea(int areaNumber)
 {
     var json = new JsonObject();
     json["command"] = "area_click";
     json["areaID"] = areaNumber;
     json["matchKeyName"] = game.Match.KeyName;
     json["playerKeyName"] = game.Player.KeyName;
     var send = "data=" + json.ToString();
     network.SendPostRequest(send);
 }
开发者ID:Sweetwater,项目名称:NetworkGame,代码行数:10,代码来源:NetworkController.cs

示例10: 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

示例11: timer_Elapsed

        void timer_Elapsed(object sender, ElapsedEventArgs e)
        {
            decimal value = Convert.ToDecimal(counter.NextValue());
            DateTime time = DateTime.Now;

            dynamic message = new JsonObject();
            message.time = time;
            message.value = value;

            SendMessage(message.ToString());
        }
开发者ID:paulbatum,项目名称:WebSocketSmoothieDemo,代码行数:11,代码来源:MonitoringService.cs

示例12: 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

示例13: SymbolFromJson

        /// <summary>
        /// Creates a symbol compatible with Application Framework from JSON object
        /// </summary>
        /// <param name="jsonObject">JSON object defining a symbol</param>
        /// <returns>Symbol</returns>
        public static Symbol SymbolFromJson(JsonObject jsonObject)
        {
            Symbol symb = null;
            if (jsonObject != null)
            {
                string symbType = jsonObject["type"];
                if (!string.IsNullOrEmpty(symbType))
                {
                    switch (symbType)
                    {
                        case "esriPMS":// REST defined PictureMarkerSymbol --> output: ImageFillSymbol 
                            #region
                            ESRI.ArcGIS.Mapping.Core.Symbols.ImageFillSymbol imgsymb = new ESRI.ArcGIS.Mapping.Core.Symbols.ImageFillSymbol();
                            double size = 64; // standard size of images used for Viewer symbols
                            if (jsonObject.ContainsKey("width") || jsonObject.ContainsKey("height"))
                            {
                                // Get the greater of the width or height, converting from points to pixels in the process
                                var pointsToPixelsFactor = 4d / 3d;
                                var width = jsonObject.ContainsKey("width") ? jsonObject["width"] * pointsToPixelsFactor : 0;
                                var height = jsonObject.ContainsKey("height") ? jsonObject["height"] * pointsToPixelsFactor : 0;
                                size = width > height ? width : height;
                            }
                            imgsymb.Size = size;
                            if (jsonObject.ContainsKey("xoffset"))
                                imgsymb.OriginX = (size /2 + jsonObject["xoffset"]) / size;
                            if (jsonObject.ContainsKey("yoffset"))
                                imgsymb.OriginY = (size / 2 + jsonObject["yoffset"]) / size;
                            if (jsonObject.ContainsKey("imageData"))
                                imgsymb.ImageData = jsonObject["imageData"];
                            else if (jsonObject.ContainsKey("url"))
                                imgsymb.Source = jsonObject["url"];

                            var fill = imgsymb.Fill as ImageBrush;
                            if (fill != null)
                                fill.Stretch = Stretch.Uniform;

                            symb = imgsymb;
                            break;
                            #endregion
                        default:
                            // all other REST defined cases
                            symb = Symbol.FromJson(jsonObject.ToString());
                            break;
                    }
                }
            }
            return symb;
        }
开发者ID:Esri,项目名称:arcgis-viewer-silverlight,代码行数:53,代码来源:SymbolJsonHelper.cs

示例14: 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

示例15: OnMessage

        public override void OnMessage(string value)
        {
            try
            {
                // クライアントからメッセージが来た場合
                JsonObject jsonValue = (JsonObject)JsonValue.Parse(value);
                this.EmailAddress = (string)((JsonPrimitive)jsonValue["address"]).Value;
                this.Password = (string)((JsonPrimitive)jsonValue["password"]).Value;

                // Exchange Online に接続 (今回はデモなので、Address は決めうち !)
                ExchangeVersion ver = new ExchangeVersion();
                ver = ExchangeVersion.Exchange2010_SP1;
                sv = new ExchangeService(ver, TimeZoneInfo.FindSystemTimeZoneById("Tokyo Standard Time"));
                //sv.TraceEnabled = true; // デバッグ用
                sv.Credentials = new System.Net.NetworkCredential(
                    this.EmailAddress, this.Password);
                sv.EnableScpLookup = false;
                sv.AutodiscoverUrl(this.EmailAddress, AutodiscoverCallback);

                // Streaming Notification の開始 (今回はデモなので、15 分で終わり !)
                StreamingSubscription sub = sv.SubscribeToStreamingNotifications(
                    new FolderId[] { new FolderId(WellKnownFolderName.Calendar) }, EventType.Created, EventType.Modified, EventType.Deleted);
                subcon = new StreamingSubscriptionConnection(sv, 15); // only 15 minutes !
                subcon.AddSubscription(sub);
                subcon.OnNotificationEvent += new StreamingSubscriptionConnection.NotificationEventDelegate(subcon_OnNotificationEvent);
                subcon.Open();

                // 準備完了の送信 !
                JsonObject jsonObj = new JsonObject(
                    new KeyValuePair<string, JsonValue>("MessageType", "Ready"),
                    new KeyValuePair<string, JsonValue>("ServerUrl", sv.Url.ToString()));
                this.SendMessage(jsonObj.ToString());
            }
            catch (Exception ex)
            {
                this.SendInternalError(ex);
            }

            base.OnMessage(value);
        }
开发者ID:tsmatsuz,项目名称:20110629_ExchangeOnlineSample,代码行数:40,代码来源:MyNotifyService.cs


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