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


C# Dictionary.ToJson方法代码示例

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


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

示例1: Build

        public override HttpRequest Build(string path)
        {
            var request = base.Build(path);
            request.Method = HttpMethod.POST;
            request.Headers.Accept = "application/json-rpc, application/json";
            request.Headers.ContentType = "application/json-rpc";

            var message = new Dictionary<string, object>();
            message["jsonrpc"] = "2.0";
            message["method"] = Method;
            message["params"] = Parameters;
            message["id"] = CreateNextId();

            request.Body = message.ToJson();

            return request;
        }
开发者ID:Djohnnie,项目名称:Sonarr,代码行数:17,代码来源:JsonRpcRequestBuilder.cs

示例2: Test_Serialize_Dictionary_02

        public static void Test_Serialize_Dictionary_02(DictionaryRepresentation dictionaryRepresentation)
        {
            // json Dictionary
            // DictionaryRepresentation.Dynamic or DictionaryRepresentation.Document
            // { "toto1" : "tata1", "toto2" : "tata2" }
            // DictionaryRepresentation.ArrayOfArrays
            // [["toto1", "tata1"], ["toto2", "tata2"]]
            // DictionaryRepresentation.ArrayOfDocuments
            // [{ "k" : "toto1", "v" : "tata1" }, { "k" : "toto2", "v" : "tata2" }]
            Trace.WriteLine();
            Trace.WriteLine("Test_Serialize_Dictionary_02");
            Dictionary<string, string> dictionary = new Dictionary<string, string>();
            dictionary.Add("toto1", "tata1");
            dictionary.Add("toto2", "tata2");
            //DictionaryRepresentation dictionaryRepresentation = DictionaryRepresentation.ArrayOfDocuments;
            Trace.WriteLine("DictionaryRepresentation : {0}", dictionaryRepresentation);
            Trace.WriteLine("Dictionary json :");
            string json = dictionary.ToJson(new DictionarySerializationOptions(dictionaryRepresentation));
            Trace.WriteLine(json);

            Trace.WriteLine("Deserialize json :");
            Dictionary<string, string> dictionary2 = BsonSerializer.Deserialize<Dictionary<string, string>>(json);
            string json2 = dictionary2.ToJson(new DictionarySerializationOptions(dictionaryRepresentation));
            Trace.WriteLine(json2);
            Trace.WriteLine("comparison of Dictionary json and Deserialize json : {0}", json == json2 ? "identical" : "different");
        }
开发者ID:labeuze,项目名称:source,代码行数:26,代码来源:Test_Bson_f.cs

示例3: BroadcastExpireCache

 public void BroadcastExpireCache(string cacheName, string key, string itemKey)
 {
     var args = new Dictionary<string, object>() { { "clientId", ClientId }, { "cacheName", cacheName }, { "key", key }, { "itemKey", itemKey } };
     var subscriber = _multiplexer.GetSubscriber();
     subscriber.Publish("RedisNotifier.expireItemCache", args.ToJson());
     log(Logging.LoggingLevel.Detailed, "Broadcasting ExpireCache: {0}:{1}", key, itemKey);
 }
开发者ID:jonhenning,项目名称:CodeEndeavors-DistributedCache,代码行数:7,代码来源:RedisNotifier.cs

示例4: BroadcastMessage

 public void BroadcastMessage(string message)
 {
     var args = new Dictionary<string, object>() { { "clientId", ClientId }, { "message", message } };
     var subscriber = _multiplexer.GetSubscriber();
     subscriber.Publish("RedisNotifier.serverMessage", args.ToJson());
     log(Logging.LoggingLevel.Detailed, "Broadcasting Message: " + message);
 }
开发者ID:jonhenning,项目名称:CodeEndeavors-DistributedCache,代码行数:7,代码来源:RedisNotifier.cs

示例5: GetEnvDataAsJson

        /// <summary>
        /// Returns the environment data as json.
        /// </summary>
        /// <returns>a JSON formatted string</returns>
        public static string GetEnvDataAsJson( System.Web.HttpRequest request, string rockUrl )
        {
            var envData = new Dictionary<string, string>();
            envData.Add( "AppRoot", rockUrl );
            envData.Add( "Architecture", ( IntPtr.Size == 4 ) ? "32bit" : "64bit" );
            envData.Add( "AspNetVersion", Environment.Version.ToString() );
            envData.Add( "IisVersion", request.ServerVariables["SERVER_SOFTWARE"] );
            envData.Add( "ServerOs", Environment.OSVersion.ToString() );

            try { envData.Add( "SqlVersion", Rock.Data.DbService.ExecuteScaler( "SELECT SERVERPROPERTY('productversion')" ).ToString() ); }
            catch {}

            try
            {
                using ( var rockContext = new RockContext() )
                {
                    var entityType = EntityTypeCache.Read( "Rock.Security.BackgroundCheck.ProtectMyMinistry", false, rockContext );
                    if ( entityType != null )
                    {
                        var pmmUserName = new AttributeValueService( rockContext )
                            .Queryable().AsNoTracking()
                            .Where( v =>
                                v.Attribute.EntityTypeId.HasValue &&
                                v.Attribute.EntityTypeId.Value == entityType.Id &&
                                v.Attribute.Key == "UserName" )
                            .Select( v => v.Value )
                            .FirstOrDefault();
                        if ( !string.IsNullOrWhiteSpace( pmmUserName ) )
                        {
                            envData.Add( "PMMUserName", pmmUserName );
                        }
                    }
                }
            }
            catch { }

            return envData.ToJson();
        }
开发者ID:NewSpring,项目名称:Rock,代码行数:42,代码来源:RockUpdateHelper.cs

示例6: SendLetter

        public void SendLetter(UpdateLetter updateLetter)
        {
            var letter = updateLetter.CreateLetter();
            letter.ReplyTime = SqlDateTime.MinValue.Value;
            using (var content = new DefaultContext())
            {
                content.Letters.Add(letter);
                content.SaveChanges();
            }
            var dic = new Dictionary<string, string>();
            dic.Add("ActionName", "Reply");
            dic.Add("letter", letter.ToJson());

            var resString = HttpWebResponseUtility.CreatePostHttpResponse("http://second.eagle.com/api/Message", dic.ToJson(), 30000);
            if (string.IsNullOrEmpty(resString) || resString == "0")
            {
                Flag = false;
                Message = "消息无响应";
                return;
            }
            var result = resString.ToDeserialize<Cells>();
            if (!result.Flag)
            {
                Flag = false;
                Message = result.Message;
                return;
            }
            Flag = true;
        }
开发者ID:key-value,项目名称:Eagle.First,代码行数:29,代码来源:LetterServices.cs

示例7: SendCancelResult

        protected virtual void SendCancelResult()
        {
            var dictionary = new Dictionary<string, object>();
            dictionary[Constants.CancelledKey] = true;
            if (!string.IsNullOrEmpty(this.CallbackID))
            {
                dictionary[Constants.CallbackIdKey] = this.CallbackID;
            }

            this.Callback(new ResultContainer(dictionary.ToJson()));
        }
开发者ID:flicknewb,项目名称:ARG-Zombies-Scaffolding,代码行数:11,代码来源:EditorFacebookMockDialog.cs

示例8: Test_Serialize_Dictionary_01

 public static void Test_Serialize_Dictionary_01()
 {
     // json Dictionary
     // { "toto1" : "tata1", "toto2" : "tata2" }
     Trace.WriteLine();
     Trace.WriteLine("Test_Serialize_Dictionary_01");
     Dictionary<string, string> dictionary = new Dictionary<string, string>();
     dictionary.Add("toto1", "tata1");
     dictionary.Add("toto2", "tata2");
     Trace.WriteLine("Dictionary json :");
     string json = dictionary.ToJson();
     Trace.WriteLine(json);
 }
开发者ID:labeuze,项目名称:source,代码行数:13,代码来源:Test_Bson_f.cs

示例9: RegisterControlPresenter

        public static void RegisterControlPresenter(this HtmlHelper helper, Models.IClientControl model, string clientType, string instanceName, Dictionary<string, object> properties = null)
        {
            properties = properties == null ? new Dictionary<string, object>() : properties;
            RegisterCoreScripts(helper);

            if (!string.IsNullOrEmpty(model.ScriptPath))
                HtmlExtensions.RegisterScript(helper, model.ScriptPath + clientType + ".js", true);

            properties["id"] = model.ClientId;  //todo: not necessary now... same as ns?
            properties["ns"] = model.ClientId;

            //Properties["user"] = Services.Account.GetClientUser();
            //var ser = new System.Web.Script.Serialization.JavaScriptSerializer();   //no binders for date conversions...
            HtmlExtensions.RegisterDocumentReadyScript(helper, model.ClientId + "Presenter", string.Format("videre.widgets.register('{0}', {1}, {2});", model.ClientId, clientType, properties.ToJson(ignoreType: "client")));
        }
开发者ID:jonhenning,项目名称:videre,代码行数:15,代码来源:PortalExtensions.cs

示例10: ToJsonTest

        public void ToJsonTest()
        {
            Dictionary<string, object> data = new Dictionary<string, object>();
            data.Add("Name", "11");
            data.Add("Teacher", new { Name = "theacher", Couse = "English" });
            data.Add("Family", new Dictionary<string, object>()
                                    {
                                        {"facther",new {Name="john",Birthday=new DateTime(1979,1,1)}},
                                        {"mother",new {Name="Hellen",Birthday=new DateTime(1979,1,1)}},
                                    });
            var expect = "{\"Name\":\"11\",\"Teacher\":{\"Name\":\"theacher\",\"Couse\":\"English\"},\"Family\":{\"facther\":{\"Name\":\"john\",\"Birthday\":\"\\/Date(283968000000)\\/\"},\"mother\":{\"Name\":\"Hellen\",\"Birthday\":\"\\/Date(283968000000)\\/\"}}}";

            var target = data.ToJson(false);
            Assert.AreEqual(expect, target);
        }
开发者ID:luqizheng,项目名称:Qi4Net,代码行数:15,代码来源:JsonHelperTest.cs

示例11: Generate

        internal static JsonObject Generate(IEnumerable<FieldInput> fields)
        {
            var jsonObject = new JsonObject();
            var list = new Dictionary<string, object>();

            if (fields != null)
            {
                foreach (var f in fields.Where(f => f.Value != null))
                {
                    list.Add(f.Id, ComplexIssueInputFieldValueJsonGenerator.GenerateFieldValueForJson(f.Value));
                }
            }

            jsonObject.Add("fields", list.ToJson());
            return jsonObject;
        }
开发者ID:Tdue21,项目名称:Jira-Rest-Client-Dot-Net-Update,代码行数:16,代码来源:IssueUpdateJsonGenerator.cs

示例12: Call

        public XDocument Call(string url, HttpMethod method, Dictionary<string, object> data, bool requiresAuthentication)
        {
            if (requiresAuthentication && (string.IsNullOrEmpty(this.publicKey) || string.IsNullOrEmpty(this.privateKey)))
            {
                throw new MyGengoException("This API requires authentication. Both a public and private key must be specified.");
            }

            var parameters = new Dictionary<string, string>();
                        parameters.Add("api_key", this.publicKey);

                        if (requiresAuthentication)
                        {
                            parameters.Add("ts", DateTime.UtcNow.SecondsSinceEpoch().ToString());
                            parameters.Add("api_sig", Sign(parameters["ts"]));
                        }

                        if (data != null)
                        {
                            parameters.Add("data", data.ToJson());
                        }

            string queryString = MakeQueryString(parameters);
            string xml = SendRequest(method, url, queryString);

            XDocument doc;
            try
            {
                doc = XDocument.Parse(xml);
            }
            catch (Exception x)
            {
                var mgx = new MyGengoException("The response returned by myGengo is not valid XML", x);
                mgx.Data.Add("url", url);
                mgx.Data.Add("response", xml);
                throw mgx;
            }

            if (doc.Root.Element("opstat").Value == "error")
            {
                XElement error = doc.Root.Element("err");
                throw new MyGengoException(string.Format("{0} (error code {1})", error.Element("msg").Value, error.Element("code").Value));
            }

            return doc;
        }
开发者ID:SaqibS,项目名称:mygengo-csharp,代码行数:45,代码来源:ApiHelper.cs

示例13: IncrementVotableVersion

        internal void IncrementVotableVersion()
        {

            foreach (var subscriber in subscribedUsers)
            {
                var votablePropsDict = new Dictionary<string, dynamic>() { 
                    { "Id", Id }, 
                    { "PositiveVotesCount", PositiveVotesCount }, 
                    { "NegativeVotesCount", NegativeVotesCount }
                };
                var opDict = new Dictionary<string, object>() { { "operation", 'u' }, { "entity", votablePropsDict } };

                var socket = subscriber.Value.connection;
                var serialized = opDict.ToJson();
                socket.Send(serialized);

            }
        }
开发者ID:capaj,项目名称:Democracy-2.0,代码行数:18,代码来源:VotableItem.cs

示例14: Work

 public void Work(string sqlText)
 {
     var restPace = new RestPace();
     restPace.ID = Guid.NewGuid();
     restPace.SqlCommand = sqlText;
     restPace.SendTime = DateTime.Now;
     restPace.ReceiveTime = SqlDateTime.MinValue.Value;
     restPace.RestaurantId = RestaurantId;
     restPace.ReceiptText = new List<List<string>>().ToJson();
     using (var restContext = new DefaultContext())
     {
         restContext.RestPaces.Add(restPace);
         restContext.SaveChanges();
     }
     var dic = new Dictionary<string, string>();
     dic.Add("messageID", restPace.ID.ToString());
     dic.Add("text", sqlText);
     PushCommandToRest(dic.ToJson());
 }
开发者ID:key-value,项目名称:Eagle.First,代码行数:19,代码来源:SendSqlCommand.cs

示例15: ExecuteScriptedEvent

 /// <summary>
 /// Executes the scripted event.
 /// </summary>
 /// <param name="eventType">Type of the event.</param>
 /// <param name="taskId">The task id.</param>
 /// <param name="name">The name.</param>
 /// <param name="sourceCode">The source code.</param>
 /// <param name="language">The language.</param>
 /// <param name="sender">The sender.</param>
 /// <param name="scriptArguments">The <see cref="System.EventArgs"/> instance containing the event data.</param>
 /// <param name="preview">if set to <c>true</c> [preview].</param>
 /// <returns></returns>
 public static Dictionary<string, object> ExecuteScriptedEvent(string eventType, Guid taskId, string name, string sourceCode, string language, object sender, EventArgs scriptArguments, bool preview)
 {
     ("EVENT " + eventType + " > delegate " + name + "(" + taskId.ToString() + ")").Debug(10);
     Dictionary<string, object> j = new Dictionary<string, object>();
     string consoleOutput = "";
     string errorNumber = "";
     string errorJSON = "";
     DateTime startDate = DateTime.Now;
     List<object> errors = new List<object>();
     object[] args = { sender, scriptArguments };
     object obj = Admin.ExecuteScript(sourceCode, language, "script", "main", ref args, ref errors);
     if(errors.Count == 0) {
         if(consoleOutput.Length > 0) {
             if(obj.GetType() == typeof(string)) {
                 consoleOutput = (string)obj;
             }
             Dictionary<string, object> err = new Dictionary<string, object>();
             err.Add("errorNumber", 0);
             err.Add("errorText", "EVENT " + eventType + " > delegate " + name + " completed without error.");
             (" --------------------------------------------------").Debug(6);
             (" |		MESSAGE FROM " + name).Debug(6);
             (" --------------------------------------------------").Debug(6);
             (consoleOutput).Debug(6);/*MESSAGE!*/
             (" --------------------------------------------------").Debug(6);
             err.Add("line", 0);
             errorNumber = "0";
             errorJSON = err.ToJson();
             err["errorText"].Debug(6);
         }
     } else {
         errorJSON = errors.ToJson();
         errorNumber = (string)((Dictionary<string, object>)(errors[0]))["errorNumber"].ToString();
         errorJSON.Debug(6);
     }
     if(!preview) {
         updateEventTaskStatus(taskId, startDate, false, DateTime.Now, errorNumber, errorJSON);
     }
     j.Add("error", errorNumber);
     j.Add("errors", errors);
     j.Add("console", consoleOutput);
     return j;
 }
开发者ID:CorbinDallas,项目名称:Rendition,代码行数:54,代码来源:Scheduler.cs


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