将字典字符串字符串转换为json字符串[重复]
Posted
技术标签:
【中文标题】将字典字符串字符串转换为json字符串[重复]【英文标题】:converting dictionary string string to json string [duplicate] 【发布时间】:2014-07-06 22:12:21 【问题描述】:如何转换我的字典
Dictionary<string,string> to JSON string
然后再次从 JSON 字符串转换为
Dictionary<string,string> in c#?
【问题讨论】:
【参考方案1】:使用扩展方法试试这个。
public static class Extensions
public static string FromDictionaryToJson(this Dictionary<string, string> dictionary)
var kvs = dictionary.Select(kvp => string.Format("\"0\":\"1\"", kvp.Key, string.Concat(",", kvp.Value)));
return string.Concat("", string.Join(",", kvs), "");
public static Dictionary<string, string> FromJsonToDictionary(this string json)
string[] keyValueArray = json.Replace("", string.Empty).Replace("", string.Empty).Replace("\"", string.Empty).Split(',');
return keyValueArray.ToDictionary(item => item.Split(':')[0], item => item.Split(':')[1]);
以下是您之后的使用方法。
class Program
static void Main(string[] args)
Dictionary<string, string> dictss = new Dictionary<string, string>();
dictss.Add("onekey", "oneval");
dictss.Add("twokey", "twoval");
dictss.Add("threekey", "threeval");
dictss.Add("fourkey", "fourval");
dictss.Add("fivekey", "fiveval");
string jsonString = dictss.FromDictionaryToJson(); //call extension method
Console.WriteLine(jsonString);
Dictionary<string, string> dictss2 = jsonString.FromJsonToDictionary(); //call extension method
foreach(KeyValuePair<string,string> kv in dictss2)
Console.WriteLine(string.Format("key=0,value=1", kv.Key, kv.Value));
或者使用普通函数
public string FromDictionaryToJson(Dictionary<string, string> dictionary)
var kvs = dictionary.Select(kvp => string.Format("\"0\":\"1\"", kvp.Key, string.Join(",", kvp.Value)));
return string.Concat("", string.Join(",", kvs), "");
public Dictionary<string, string> FromJsonToDictionary(string json)
string[] keyValueArray = json.Replace("", string.Empty).Replace("", string.Empty).Replace("\"", string.Empty).Split(',');
return keyValueArray.ToDictionary(item => item.Split(':')[0], item => item.Split(':')[1]);
【讨论】:
不应该是var kvs = dictionary.Select(kvp => string.Format("\"0\":\"1\"", kvp.Key, kvp.Value));
吗?否则所有值都以逗号开头...
在FromJsonToDictionary
中,你可以通过keyValueArray.Select(t => t.Split(':')).ToDictionary(item => item[0], item => item[1])
避免两次split(':')
你应该在你做 string.Join("," ...以上是关于将字典字符串字符串转换为json字符串[重复]的主要内容,如果未能解决你的问题,请参考以下文章
如何将afnetworking json字典转换为字符串,然后在IOS中将字符串转换为字典?