3

How can i convert my dictionary

Dictionary<string,string> to JSON string 

and then again convert from JSON string to

Dictionary<string,string> in c#?
0

1 Answer 1

10

Try this using extension methods.

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]);
    }
}

Here is how you would use them after.

    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));
        }
    }

Or using plain functions

        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]);
        }
Sign up to request clarification or add additional context in comments.

3 Comments

Should it not be var kvs = dictionary.Select(kvp => string.Format("\"{0}\":\"{1}\"", kvp.Key, kvp.Value)); ? Otherwise all values are preceded by a comma...
In FromJsonToDictionary you can avoid doing split(':') twice by doing keyValueArray.Select(t => t.Split(':')).ToDictionary(item => item[0], item => item[1])
your should trim the start when you do string.Join("," ...

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.