Home > OS >  Converting a string to a Dictionary of Dictionary<string, List<string>> in C#
Converting a string to a Dictionary of Dictionary<string, List<string>> in C#

Time:09-29

I have the follow string:

string mystring = "{yhxj7027DO=[3], lzpd7453EH=[2, 3]}"

I would like to convert it to a Dictionary of type Dictionary<string, List<string>>, where a key for example can be yhxj7027DO; and a value [3]

I tried Dictionary<string, List<string>> test = JsonConvert.DeserializeObject<Dictionary<string, List<string>>(mystring); but it does not work. What is wrong in my code?

CodePudding user response:

your string has nothing to do with json, but you can convert it to json

     string mystring = "{yhxj7027DO=[3], lzpd7453EH=[2, 3]}";

    var strArr = mystring.Replace("{", "").Replace("}", "").Split("],", StringSplitOptions.TrimEntries);
    for (int i = 0; i < strArr.Length - 1; i  ) strArr[i]  = "]";
    StringBuilder sb = new StringBuilder("{");
    foreach (var item in strArr)
    {
        var arr = item.Split("=");
        sb.Append("\""   arr[0]   "\""   ":"   arr[1]   ",");
    }

    sb.Append("}");
    var json = sb.ToString().Replace(",}", "}");

    Dictionary<string, int[]> result=JsonConvert.DeserializeObject<Dictionary<string, int[]>>(json);

result

{"yhxj7027DO":[3],"lzpd7453EH":[2, 3]}
  • Related