/// <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;
}
调用方法:
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;
}
返回结果:
{"address":"重庆","sex":"男","username":"张三"}