青春年华

把字典型转化为Json类型

电脑版发表于:2020/6/18 17:42
```csharp
   /// <summary>
        /// 字典转json
        /// </summary>
        /// <param name="dir"></param>
        /// <returns></returns>
        public   string ToJson(Dictionary<string, string> dir)
        {
            string json = string.Empty;
            if (dir.Count > 0)
            {
                var newdir = dir.OrderBy(i => i.Key).ToList();
                json += "{";
                foreach (var newd in newdir)
                {
                    if (newd.Value.StartsWith("[") || newd.Value.StartsWith("{") || newd.Value.StartsWith("\""))
                    {
                        json += string.Format("\"{0}\":{1},", newd.Key, newd.Value);
                    }
                    else
                    {
                        json += string.Format("\"{0}\":\"{1}\",", newd.Key, newd.Value);
                    }
                }
                if (json.EndsWith(","))
                {
                    json = json.Substring(0, json.Length - 1);
                }
                json += "}";
            }
            else
            {
                json = "{}";
            }
            return json;
        }
```
**调用方法:**
```csharp
 public    string Dictionary_json()
        {
            Dictionary<string, string> postDir = new Dictionary<string, string>();
            postDir.Add("username", "张三");
            postDir.Add("sex", "男");
            postDir.Add("address", "重庆");
            var result = new  yunxinApi().ToJson(postDir);
            return result;
        }
```
**返回结果:**
```csharp
{"address":"重庆","sex":"男","username":"张三"}
```


关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢